Sub topic 15
Subclassing with extends and super
This chapter assumes you know the prototype chain, how new works with constructor functions, the pre-class inheritance pattern built from Object.create and Parent.call(this), and basic class syntax. The extends and super keywords replace that manual wiring. They also add a few rules that the old pattern did not have.
What extends Wires Up
Writing class Dog extends Animal creates two prototype links:
Dog.prototypegetsAnimal.prototypeas its[[Prototype]]. Instances therefore inherit instance methods.Dogitself getsAnimalas its[[Prototype]]. The constructors are linked, so static members are inherited. The next chapter covers this link.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // run Animal's constructor for this instance
this.breed = breed; // safe only after super()
}
speak() {
return `${super.speak()}, woof`;
}
}
const rex = new Dog('Rex', 'beagle');
console.log(rex.speak()); // "Rex makes a sound, woof"
console.log(rex.breed); // "beagle"
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype); // true
console.log(Object.getPrototypeOf(Dog) === Animal); // trueThe right-hand side of extends can be any expression that evaluates to a constructor or to null. That includes old-style constructor functions:
function Legacy(name) {
this.name = name;
}
Legacy.prototype.hello = function () {
return `hello ${this.name}`;
};
class Modern extends Legacy {
hello() {
return super.hello().toUpperCase();
}
}
console.log(new Modern('ada').hello()); // "HELLO ADA"If the expression is not a constructor, such as an arrow function or a plain object, the engine throws a TypeError while it evaluates the class definition.
The Derived Constructor Rule: super() Before this
A class that uses extends has a derived constructor, and a derived constructor does not create its own object. With a constructor function, new builds the object first and then runs the function on it. In a derived class, the base class creates the object, and super(...) is the call that triggers it. Until super() returns, this is uninitialized.
class Animal {
constructor(name) {
this.name = name;
}
}
class Broken extends Animal {
constructor(name) {
this.name = name; // ReferenceError: this is not initialized yet
super(name);
}
}
class Forgetful extends Animal {
constructor(name) {
// never calls super()
}
}
try { new Broken('x'); } catch (e) { console.log(e.name); } // "ReferenceError"
try { new Forgetful('x'); } catch (e) { console.log(e.name); } // "ReferenceError"These are the rules:
- You must call
super()before you read or writethis, and before the constructor returns. The only exception is a constructor that returns an object explicitly. - Calling
super()twice throws aReferenceError, becausethisis already initialized. - If you leave out the constructor, the engine supplies
constructor(...args) { super(...args); }. Write your own constructor only when you need to change the arguments or add setup.
Because the base constructor allocates the object, subclassing built-ins like Array, Map, or Error works properly with extends. The old Parent.call(this) pattern could not do this.
class Stack extends Array {
peek() {
return this[this.length - 1];
}
}
const s = new Stack();
s.push(1, 2, 3);
console.log(s.peek()); // 3
console.log(Array.isArray(s)); // true
console.log(s.map(x => x * 2).peek()); // 6, because map returns a StackThe Two Forms of super
| Form | Where it is allowed | What it does |
|---|---|---|
| `super(...args)` | Only in a derived class constructor | Calls the parent constructor and initializes `this` |
| `super.method(...)` | Any method, including static methods, getters, setters, and arrow functions defined inside them | Looks up `method` starting at the parent prototype and calls it with the current `this` |
| `super.prop` | Same as above | Reads a property starting at the parent prototype |
Arrow functions do not have their own super. They take it from the method they are defined in, just as they take this. A callback such as items.map(x => super.format(x)) inside a method works as you would hope.
How super.method Finds the Parent: [[HomeObject]]
super does not look at this to find the parent. If it did, a three-level hierarchy would loop: a method on the middle class would resolve super relative to the bottom class's instance and call itself forever. Instead, each method defined with method syntax records an internal [[HomeObject]], the object it was defined on. super.x starts its lookup at Object.getPrototypeOf([[HomeObject]]).
This binding is fixed when the method is defined. Copying the method to another object does not change it:
class A { hi() { return 'A'; } }
class B extends A { hi() { return `B>${super.hi()}`; } }
class C { hi() { return 'C'; } }
class D extends C {}
D.prototype.hi = B.prototype.hi; // borrow B's method
console.log(new D().hi()); // "B>A", not "B>C"The borrowed method still calls A.prototype.hi, because its home object is B.prototype. Keep this in mind when you copy methods between classes or onto prototypes. A copied method that uses super keeps pointing at its original parent.
Gotcha: Class Fields and Overridden Methods Called from the Parent
A derived class's fields are initialized right after super() returns, not before. If the parent constructor calls a method that the child overrides, that method runs before the child's fields exist:
class Base {
constructor() {
this.init();
}
init() {}
}
class Widget extends Base {
label = 'default';
init() {
console.log(`init sees: ${this.label}`);
}
}
const w = new Widget(); // "init sees: undefined"
console.log(w.label); // "default"The order is: Widget's implicit constructor calls super(), Base runs and calls this.init(), which resolves to Widget.prototype.init, then super() returns and label is assigned. The usual fixes are to avoid calling overridable methods from constructors, to pass values as constructor arguments, or to run the setup in a separate step after construction.
Exercises
Exercise
What does this print, and why? class P { constructor() { this.kind = 'P'; } } class Q extends P { constructor() { super(); this.kind += 'Q'; } } console.log(new Q().kind);
Show answer
It prints "PQ". super() runs P's constructor on the new object and sets kind to 'P'. Then Q's constructor appends 'Q'. Doing the append before super() would throw a ReferenceError.
Exercise
A method describe() { return super.describe() + '!'; } is defined in class Cat extends Pet. Someone copies it with Robot.prototype.describe = Cat.prototype.describe, where Robot extends Machine. Which describe does super call when robot.describe() runs?
Show answer
It calls Pet.prototype.describe. super is resolved from the method's [[HomeObject]] (Cat.prototype), whose prototype is Pet.prototype. Neither the receiver robot nor Robot's own parent affects the lookup, though this inside Pet's describe will still be robot.
Exercise
In a subclass, a field items = [] is declared, and the parent constructor calls this.reset(), which the subclass overrides to run this.items.length = 0. What happens on new, and how would you fix it?
Show answer
It throws a TypeError, because reset runs during super(), before the items field is initialized, so this.items is undefined. Fixes include not calling overridable methods from the parent constructor, guarding inside reset, or calling reset after construction.