Sub topic 3
Classes Are Built on Prototypes
This chapter assumes you know how the prototype chain works, what new does, and how constructor functions use their prototype property.
Classes Are Built on Prototypes
A class declaration creates a constructor function. Its methods go on ClassName.prototype, the same place you would put them by hand. Unlike a plain function, a class throws an error if you call it without new.
Subclassing with extends and super
extends makes two links. Dog.prototype inherits from Animal.prototype, so instances get the parent's methods. Dog itself inherits from Animal, so static members are inherited too. Inside a method, super.method() calls the parent's version with the current this.
Static Members and Inherited Constructors
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
static create(name) {
return new this(name);
}
}
class Dog extends Animal {
speak() {
return `${super.speak()}, woof`;
}
}
const rex = Dog.create('Rex');
console.log(rex.speak()); // "Rex makes a sound, woof"
console.log(typeof Dog); // "function"
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype); // true
console.log(Object.getPrototypeOf(Dog) === Animal); // trueDog.create is found on Animal. Because the call is made through Dog, this is Dog, so the method builds a Dog.
Type Checks with instanceof and isPrototypeOf
rex instanceof Dog checks whether Dog.prototype appears anywhere in the prototype chain of rex. Animal.prototype.isPrototypeOf(rex) runs the same check without needing a constructor. Both checks give the wrong answer across realms. An array created in an iframe fails instanceof Array, so use Array.isArray for arrays.
Built-in Prototypes and Why You Should Not Modify Them
When you add methods to Array.prototype or Object.prototype, every object in the program sees them. Your additions can collide with future standard methods. Libraries that did this held back new names in the language: Array.prototype.flatten had to be renamed flat for that reason. Additions also show up in for...in loops.
Objects Without a Prototype: Object.create(null)
const dict = Object.create(null);
dict.apple = 3;
console.log('toString' in dict); // false
console.log(Object.keys(dict)); // ['apple']An object created with Object.create(null) has no inherited keys. That makes it a safe dictionary for keys supplied by users.
Sharing Behavior with Mixins and Composition
const Serializable = {
toJSONString() {
return JSON.stringify(this);
}
};
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
Object.assign(Point.prototype, Serializable);
console.log(new Point(1, 2).toJSONString()); // '{"x":1,"y":2}'Object.assign copies the methods onto the prototype. Unrelated classes can share behavior this way without adding another level to the chain.
Performance: Why Changing Prototypes at Runtime Is Discouraged
JavaScript engines optimize property access based on an object's shape and its prototype. When you call Object.setPrototypeOf on an existing object, those optimizations are thrown away, and the slowdown can spread to code that touches that object. Pick the prototype when you create the object, with Object.create or class.
Exercise
Given class B extends A {}, what do Object.getPrototypeOf(B) and Object.getPrototypeOf(B.prototype) return?
Show answer
A and A.prototype. The first link makes static members inherited. The second makes instance methods inherited.
Exercise
Why does obj.hasOwnProperty('x') throw when obj was made with Object.create(null), and what should you use instead?
Show answer
The object does not inherit from Object.prototype, so it has no hasOwnProperty method. Use Object.hasOwn(obj, 'x') instead.