So that the static methods of the parent class are inherited by the subclass, because they've made the parent class constructor the prototype of the child class constructor.
Native class
syntax does the same thing:
class Parent {
static example() {
console.log("Parent.example");
}
}
class Child extends Parent {
}
console.log(Child.example()); // "Parent.example"
console.log(Child.hasOwnProperty("example")); // false
console.log("example" in Child); // true, because it's inherited
console.log(Object.getPrototypeOf(Child) === Parent); // true
Remember that functions are objects. Objects can have prototypes. An object inherits properties from its prototype. In the example above, Child
(the function objects) has Parent
(the function object) as its prototype, so it inherits the example
property. Up through ES5, a function created with JavaScript code always had Function.prototype
as its prototype, but starting with ES2015, that's not always true. class
syntax makes the superclass constructor the prototype of the subclass constructor. You can also change the prototype of a function after it's created, via Object.setPrototypeOf
, but it's usually best to avoid changing the prototype of an existing object.
In Chapter 4 of my new book JavaScript: The New Toys, I use the following example to illustrate this concept (details omitted):
class Color {
}
class ColorWithAlpha {
}
along with this diagram to show the two parallel prototype chains created by that, one for the constructor functions themselves, and the other for the objects they assign as prototype when used to create objects:
