How do classes relate to prototypes?
A JavaScript class is really a constructor function with a prototype object attached to it. When you write a class, the engine creates the constructor function for you and puts the methods on its prototype. That is exactly the same thing you would do by hand, so the class syntax does not create a new model. It only gives you a clearer and stricter way to write the old one.
class Greeter {
constructor(name) {
this.name = name;
}
greet() {
return 'Hi ' + this.name;
}
}
const greeter = new Greeter('Ada');
console.log(greeter.greet()); // Hi Ada
// The class is a constructor function and its methods live on the prototype.
console.log(typeof Greeter); // function
console.log(Object.getPrototypeOf(greeter) === Greeter.prototype); // true
An instance still works in the same way that it always has. It does not hold a copy of the methods. It holds a link to the class prototype, and reading a method walks along that link. The instanceof check works the same way too, because it compares the prototype chain against the constructor's prototype.
The class syntax adds three things on top of the raw mechanism. The body is always in strict mode, so the loose-mode surprises with this and with accidental globals are gone. The methods are not enumerable, which means they do not show up when you iterate the prototype with a for...in loop or with the keys method. And calling a class without the new keyword throws a TypeError instead of running the body with an unexpected this.