Sub topic 11
The constructor Property
This chapter assumes you know how constructor functions and their prototype property work, what new does, and how to check own properties with Object.hasOwn. Those topics were covered in the previous chapters.
Every ordinary function gets a prototype object when it is created. That object comes with one property already on it: constructor, which points back to the function. The back-reference is small and easy to break by accident. Code that depends on it can fail in ways that are hard to trace.
The Default Back-Reference
When JavaScript creates a function that can be used with new, it also creates F.prototype and sets F.prototype.constructor = F. Instances do not get their own copy. They inherit constructor through the prototype chain.
function Person(name) {
this.name = name;
}
const ada = new Person('Ada');
console.log(Person.prototype.constructor === Person); // true
console.log(ada.constructor === Person); // true (inherited)
console.log(Object.hasOwn(ada, 'constructor')); // false
console.log(ada.constructor.name); // "Person"
console.log(Object.getOwnPropertyDescriptor(Person.prototype, 'constructor'));
// { value: [Function: Person], writable: true, enumerable: false, configurable: true }
console.log(Object.keys(Person.prototype)); // []The descriptor shows three things:
enumerable: falsekeepsconstructorout ofObject.keysandfor...in. This is whyPerson.prototypelooks empty when you list its keys.writable: truemeans anyone can reassign it.configurable: truemeans anyone can redefine or delete it.
When you read ada.constructor, the lookup fails on ada, moves to Person.prototype, and finds the property there. Nothing on the instance itself records which function created it.
Which Functions Have It
Not every function gets a prototype object, and not every prototype object has a constructor.
| Function kind | Has `.prototype`? | `prototype.constructor` points back? | Usable with `new`? |
|---|---|---|---|
| `function` declaration or expression | Yes | Yes | Yes |
| `class` | Yes (non-writable) | Yes | Yes (only with `new`) |
| Arrow function | No | Not applicable | No |
| Method shorthand `{ m() {} }` | No | Not applicable | No |
| `async function` | No | Not applicable | No |
| Generator `function*` | Yes | No | No |
| Bound function (`f.bind(x)`) | No | Not applicable | Yes, if `f` is |
Generators are the odd case. They have a prototype object, which becomes the prototype of the generator objects they return, but that object has no constructor property.
How Replacing the Prototype Breaks It
A common style replaces the whole prototype with an object literal so that all the methods sit together. The literal is a new object, so it has no constructor of its own. Lookups then fall through to Object.prototype.constructor, which is Object.
function Car(make) {
this.make = make;
}
Car.prototype = {
drive() {
return `${this.make} drives`;
}
};
const volvo = new Car('Volvo');
console.log(volvo.drive()); // "Volvo drives"
console.log(volvo.constructor === Car); // false
console.log(volvo.constructor === Object); // true
console.log(volvo instanceof Car); // trueinstanceof still works because it checks the prototype chain, not the constructor property. That difference hides the bug: type checks pass, and only code that reads constructor misbehaves.
Restoring It Correctly
You can fix this in three ways.
- Add methods to the existing prototype instead of replacing it (
Car.prototype.drive = function () {...}). The originalconstructorstays where it was. - Put
constructor: Carin the literal. This works, but the property becomes enumerable, so it appears infor...inloops over instances. - Redefine it with
Object.definePropertyso it matches the default descriptor.
function Car(make) {
this.make = make;
}
Car.prototype = {
drive() {
return `${this.make} drives`;
}
};
Object.defineProperty(Car.prototype, 'constructor', {
value: Car,
writable: true,
enumerable: false,
configurable: true
});
const volvo = new Car('Volvo');
console.log(volvo.constructor === Car); // true
console.log(Object.keys(Car.prototype)); // ['drive']The same problem appears when you link prototypes with Object.create(Parent.prototype) for inheritance. The chapter on inheritance before classes uses this same defineProperty fix.
A Real Use: Creating "Another One of These"
The main reason to keep constructor intact is so that a method can create a new object of the same type as this without hard-coding a constructor name. If a subtype inherits the method, it gets instances of the subtype back.
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.translate = function (dx, dy) {
return new this.constructor(this.x + dx, this.y + dy);
};
const p = new Point(1, 2);
const q = p.translate(3, 3);
console.log(q.x, q.y); // 4 5
console.log(q instanceof Point); // true
console.log(q.constructor === Point); // trueIf translate had said new Point(...), a subtype that inherited it would produce plain Point objects. Built-in methods such as Array.prototype.map follow a similar idea, though they use the more elaborate Symbol.species hook.
Why constructor Is Not a Type Check
constructor is an ordinary, writable, inherited property, so you should not use it to decide what an object is.
function Person(name) {
this.name = name;
}
const ada = new Person('Ada');
ada.constructor = Array; // creates an own property that shadows the inherited one
console.log(ada.constructor === Array); // true
console.log(ada instanceof Person); // true
const dict = Object.create(null);
console.log(dict.constructor); // undefined
console.log((5).constructor === Number); // true (primitive is boxed for the lookup)The value of constructor can be lost, replaced, shadowed, or missing entirely. Use instanceof or isPrototypeOf for type checks, which a later chapter covers. Treat constructor as a convenience for debugging (obj.constructor.name) and for the "create another one" pattern.
Classes
Class syntax sets up the same back-reference with the same descriptor: writable, configurable, and non-enumerable. One thing differs. A class's own prototype property is non-writable, so you cannot replace the whole prototype object and lose constructor that way.
class Robot {}
console.log(Robot.prototype.constructor === Robot); // true
console.log(Object.getOwnPropertyDescriptor(Robot, 'prototype').writable); // false
Robot.prototype = {}; // ignored (throws TypeError in strict mode)
console.log(Robot.prototype.constructor === Robot); // trueClasses protect only the prototype slot. Someone can still reassign Robot.prototype.constructor itself.
Exercise
After running function F() {}; F.prototype = { a: 1 }; const f = new F();, what do f.constructor === F, f.constructor === Object, and f instanceof F evaluate to, and why?
Show answer
false, true, true. The literal assigned to F.prototype has no own constructor, so the lookup continues to Object.prototype.constructor, which is Object. instanceof checks whether F.prototype appears in f's prototype chain, and it does, so the result is true.
Exercise
Why is Object.defineProperty preferred over writing constructor: F inside the replacement object literal?
Show answer
A property written in a literal is enumerable, so constructor would appear in Object.keys(F.prototype) and in for...in loops over every instance. defineProperty with enumerable: false restores the same descriptor JavaScript creates by default.
Exercise
A clone method is written as return new Point(this.x, this.y);. What goes wrong when a subtype inherits it, and how does this.constructor fix it?
Show answer
The method always creates a Point, so calling it on a subtype instance returns an object of the wrong type. new this.constructor(this.x, this.y) looks up constructor through the receiver's prototype chain and finds the subtype, as long as the subtype's constructor property is set correctly.