JavaScript classes and prototypes are not two competing systems that fight each other. They are one system wearing two different outfits. The class keyword builds a constructor function and gives that function a prototype object, and every property lookup in the language still ends with a walk up the prototype chain. Once you can see that arrangement clearly, the parts of the language that look like magic stop looking like magic. This is the first lesson in the module, and the later lessons in it build on the model that is set up here: the next lesson looks at constructors and instance state, and the one after that looks at getters, setters, and methods.
What does the class keyword actually build?
Start with the older form, which is a function that assigns properties to this together with methods bolted onto Rectangle.prototype. This is not a recommendation to write new code this way. It is simply the clearest way to see what the class form is doing underneath.
function Rectangle(width, height) {
this.width = width;
this.height = height;
}
Rectangle.prototype.area = function () {
return this.width * this.height;
};
const box = new Rectangle(3, 4);
console.log(box.area());
console.log(box instanceof Rectangle);
console.log(Object.getPrototypeOf(box) === Rectangle.prototype);
Three objects are in play here, and they are easy to confuse with one another. Rectangle is a function. Rectangle.prototype is an ordinary object that holds the shared behaviour. box is an ordinary object whose internal prototype link points at Rectangle.prototype. The new keyword runs the function with this bound to a freshly created object, points that new object's prototype at Rectangle.prototype, and hands the object back to you.
Now look at the class form, which produces exactly the same arrangement with much less ceremony.
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
const box = new Rectangle(3, 4);
console.log(box.area());
console.log(typeof Rectangle);
console.log(Object.getPrototypeOf(box) === Rectangle.prototype);
The two snippets print the same area and the same true, and the reason is that class is simply a more disciplined way of spelling the previous example. Notice what typeof Rectangle reports, which is function and not class. There is no separate class object inside the runtime. The methods that you declared inside the class body were placed on Rectangle.prototype for you, and the constructor became the function that you call with new.
Where do the methods actually live?
They live on the prototype and not on the instance. That is not a small detail, because it decides whether a method is shared by every object of that type or copied onto each one separately. Most languages copy the method. JavaScript shares it and looks it up when it is needed.
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
const box = new Rectangle(3, 4);
console.log(Object.keys(box));
console.log(box.hasOwnProperty("area"));
console.log(box.area === Rectangle.prototype.area);
console.log(Object.getOwnPropertyNames(Rectangle.prototype));
Object.keys(box) lists only width and height, which are the per-object state. The method is not among them, and hasOwnProperty("area") answers false. The method is found by walking the prototype chain instead, and box.area === Rectangle.prototype.area answers true, which means that every rectangle points at one and the same function object. Build a million rectangles and you have created one area function and not a million of them. That single fact is why a prototype-based language can afford to add a method to a type after objects of that type already exist.
What is the prototype chain, exactly?
Every object has exactly one internal link to another object, and Object.getPrototypeOf is how you look at that link from your own code. Reading a property means that you look on the object itself, and if it is not there you look on its prototype, and if it is not there you look on that object's prototype, and you keep going until you reach null.
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
const box = new Rectangle(3, 4);
const proto = Object.getPrototypeOf(box);
console.log(proto === Rectangle.prototype);
console.log(proto.hasOwnProperty("area"));
console.log(Object.getPrototypeOf(proto) === Object.prototype);
console.log(typeof box.toString);
console.log(Object.getPrototypeOf(Object.getPrototypeOf(proto)) === null);
The chain for box runs from box to Rectangle.prototype to Object.prototype and then to null. That last stop explains why every object inherits toString and hasOwnProperty without anybody defining them, and it also explains why asking for the prototype of Object.prototype gives you null rather than an error.
How does class syntax compare with a constructor function?
Both styles produce the same runtime shape. The differences are about safety and comfort, and not about what you are able to do.
| Behaviour | Constructor function | class syntax |
|---|---|---|
| Prototype methods | Assigned by hand onto Foo.prototype | Declared in the class body |
Called without new | Runs, with this set to undefined or to the global object | Throws a TypeError |
Prototype constructor property | Points at the function, but it can be clobbered by accident | Non-enumerable and always correct |
| Method enumerability | Enumerable by default when you assign it by hand | Non-enumerable |
| Reaching the parent implementation | Manual prototype juggling | super(...) and super.method() |
The second row in that table bites people most often, because a class cannot be invoked without new.
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
}
try {
Rectangle(3, 4);
} catch (err) {
console.log(err.constructor.name + ": " + err.message);
}
The message names the fix, because it tells you that a constructor needs new. The fourth row matters just as much in real code. Methods that are declared in a class body are non-enumerable, so for...in and Object.keys skip them, whereas a method that you bolted onto a prototype by hand is enumerable and shows up in both. Move a codebase from one style to the other and any code that loops over an object with for...in will quietly start behaving in a different way.
Can an object inherit without any class being involved?
Yes, and it is worth understanding because it is what class is built on anyway. Object.create takes a prototype object and returns a new object whose internal link points at it.
const greeter = {
greet() {
return this.name + " says hello";
},
};
const robot = Object.create(greeter);
robot.name = "R2";
console.log(robot.greet());
console.log(robot.hasOwnProperty("greet"));
console.log(Object.getPrototypeOf(robot) === greeter);
console.log(Object.getPrototypeOf(robot).hasOwnProperty("greet"));
The first line prints R2 says hello even though robot was created from an object literal, because greet was found by delegation. The second line prints false, because the robot never owned that function. The last two lines print true, which confirms that the prototype of the robot really is the greeter object and that greet lives on it. Sharing behaviour without copying it is the whole trick, and class syntax is simply a tidy front end for the same idea.
Quick reference: the model in five lines
- There is no separate class object inside the runtime, because
classproduces a constructor function plus a prototype object. - Behaviour lives on the prototype and is shared by every instance, while state lives on the instance and belongs to one object.
- A read walks the chain from the instance to its prototype, then to that prototype's prototype, and then to
null. Object.getPrototypeOfshows the link,hasOwnPropertyshows what is genuinely yours, andObject.keysshows your own enumerable data.- Methods can be added to a prototype after instances already exist, because nothing was ever copied.
Try it yourself: in a Node REPL or in a browser console, declare class Point { constructor(x, y) { this.x = x; this.y = y; } distanceTo(other) { return Math.hypot(this.x - other.x, this.y - other.y); } } and then create two points. Check Object.keys(p1), p1.hasOwnProperty("distanceTo"), Object.getPrototypeOf(p1) === Point.prototype, and Object.getPrototypeOf(Point.prototype) === Object.prototype, where the last two should print true. Then, after both points exist, add Point.prototype.toString = function () { return this.x + "," + this.y; } and call it on a point that you created earlier. It works, because behaviour is looked up rather than copied.