Sub topic 9
Constructor Functions and the prototype Property
This chapter assumes you know how property lookup walks the prototype chain, how Object.create sets an object's [[Prototype]], and how this refers to the receiver when an inherited method is called. Here those ideas are applied to the main way JavaScript created families of similar objects before classes existed: constructor functions.
The Problem Constructor Functions Solve
Say you need many "person" objects. Each one needs its own name, and all of them should share the same greet method. You could do it by hand with Object.create:
const personMethods = {
greet() {
return `Hi, I'm ${this.name}`;
}
};
function makePerson(name) {
const p = Object.create(personMethods);
p.name = name;
return p;
}
const ada = makePerson('Ada');
console.log(ada.greet()); // "Hi, I'm Ada"This works, but it involves three separate pieces: a methods object, a factory function, and a manual link between them. Constructor functions put these pieces into the language itself. Every ordinary function carries its own "methods object" in a property called prototype, and the new operator does the linking for you.
Every Ordinary Function Has a prototype Property
When you declare a regular function, JavaScript creates a plain object along with it and stores that object in the function's prototype property:
function Person(name) {
this.name = name;
}
console.log(typeof Person.prototype); // "object"
console.log(Object.getOwnPropertyNames(Person.prototype)); // [ 'constructor' ]
console.log(Object.getPrototypeOf(Person.prototype) === Object.prototype); // trueThe object starts out almost empty. It holds only a constructor property that points back to the function, which a later chapter covers. Its own [[Prototype]] is Object.prototype, so anything inheriting from it also gets toString, hasOwnProperty, and the other usual methods.
By convention, a function meant to be called with new has a capitalized name. The language does not enforce this. The capital letter just tells readers that the function is a constructor.
Two Different Things Called "Prototype"
The word "prototype" refers to two separate things, and mixing them up causes most of the confusion on this topic.
| Term | Belongs to | What it is | How to read it |
|---|---|---|---|
| `[[Prototype]]` | Every object | The hidden link that lookup follows | `Object.getPrototypeOf(obj)` |
| `prototype` property | Ordinary functions (and classes) | A normal property holding the object that instances will link to | `Fn.prototype` |
A function is also an object, so it has both. They point to different objects:
function Person(name) {
this.name = name;
}
console.log(Object.getPrototypeOf(Person) === Function.prototype); // true
console.log(Person.prototype === Function.prototype); // false
console.log(Object.getPrototypeOf(Person) === Person.prototype); // falseObject.getPrototypeOf(Person) is where Person itself inherits from. That is why Person.call and Person.bind work. Person.prototype is the object that instances created by new Person() will inherit from. The function does not inherit from it.
Putting Shared Methods on the prototype Object
Methods go on Person.prototype, and per-instance data goes on this inside the constructor:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
return `Hi, I'm ${this.name}`;
};
const ada = new Person('Ada');
const alan = new Person('Alan');
console.log(ada.greet()); // "Hi, I'm Ada"
console.log(alan.greet()); // "Hi, I'm Alan"
console.log(ada.greet === alan.greet); // true
console.log(Object.getPrototypeOf(ada) === Person.prototype); // true
console.log(Object.hasOwn(ada, 'greet')); // falseThere is exactly one greet function. Each instance finds it through its [[Prototype]] link, and this refers to whichever instance made the call. The next chapter walks through the steps new performs. For now, the key point is that new Person(...) creates an object whose [[Prototype]] is Person.prototype.
Methods in the Constructor versus on the prototype
You can also define methods inside the constructor:
function Counter() {
this.value = 0;
this.increment = function () {
this.value += 1;
return this.value;
};
}
const c1 = new Counter();
const c2 = new Counter();
console.log(c1.increment === c2.increment); // falseEach instance now has its own copy of increment. The trade-offs:
| Approach | Memory | Can be patched for all instances later | Can close over private variables |
|---|---|---|---|
| On `Fn.prototype` | One function shared | Yes | No |
| Inside constructor | One function per instance | No | Yes |
Use the prototype by default. Define functions per instance only when you need a closure over private state, and accept the extra cost of one function per instance.
Functions Without a prototype Property
Not every function can act as a constructor. Arrow functions, method shorthand, async functions, and most built-in methods have no prototype property, and calling them with new throws an error:
const arrow = () => {};
const obj = { method() {} };
async function load() {}
console.log(arrow.prototype); // undefined
console.log(obj.method.prototype); // undefined
console.log(load.prototype); // undefined
try {
new arrow();
} catch (e) {
console.log(e instanceof TypeError); // true
}Generator functions do have a prototype property, but new still throws for them. Classes have a prototype that is non-writable. Regular function declarations and expressions are the only plain functions that work as full constructors.
Gotcha: Replacing prototype Affects Only Future Instances
The prototype property is read when new runs. If you assign a new object to it later, existing instances keep their link to the old object:
function Widget() {}
Widget.prototype.kind = 'old';
const w1 = new Widget();
Widget.prototype = { kind: 'new' };
const w2 = new Widget();
console.log(w1.kind); // "old"
console.log(w2.kind); // "new"
console.log(w1 instanceof Widget); // false
console.log(w2.constructor === Widget); // falseThere are two consequences here. w1 instanceof Widget is now false, because instanceof checks against the current Widget.prototype. The replacement object also has no constructor property, so w2.constructor falls through to Object. To avoid both problems, add methods to the existing object (Widget.prototype.method = ...) instead of replacing it. If you do replace it, do so before you create any instances.
Exercise
Given function Car() {} and const car = new Car();, which of these are true: (a) Object.getPrototypeOf(car) === Car.prototype, (b) Object.getPrototypeOf(Car) === Car.prototype, (c) Object.getPrototypeOf(Car.prototype) === Object.prototype?
Show answer
(a) and (c) are true. (b) is false: the [[Prototype]] of Car is Function.prototype. Car.prototype is the prototype given to instances, not to Car itself.
Exercise
A teammate writes const Shape = (w) => { this.w = w; }; Shape.prototype.area = function () {};. What goes wrong, and how do you fix it?
Show answer
Arrow functions have no prototype property, so Shape.prototype is undefined and assigning .area to it throws a TypeError. new Shape() would also throw. Use a regular function instead: function Shape(w) { this.w = w; }.
Exercise
You create 10,000 instances of a constructor that defines this.render = function () {...} inside its body. How many render functions exist, and how would you reduce that to one?
Show answer
There are 10,000 render functions, one per instance. Move it to Fn.prototype.render = function () {...} so all instances share a single function through their prototype link.