extends and super
Inheritance with classes is two keywords, and both map onto prototype-chain operations you can already picture.
extends links one class's prototype to another's, so instances inherit through the same chain as always. super calls the parent constructor, and inside a method it reaches the parent's version. A subclass constructor must call super before touching this.
EXERCISE
1extends Wires Two Chains Together
The keyword does one structural thing, and seeing what it does removes any need to memorise inheritance rules.
The syntax, and what it produces:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
speak() {
return `${this.name} barks`;
}
}
const rex = new Dog("Rex");
console.log(rex.speak()); // Rex barks
console.log(rex.name); // Rex
Dog did not define a constructor and did not define name, yet rex.name works. Look at why:
console.log(Object.getPrototypeOf(rex) === Dog.prototype); // true
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype); // true
console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true
// rex -> Dog.prototype -> Animal.prototype -> Object.prototype -> null
extends inserted Animal.prototype into the chain between Dog.prototype and Object.prototype. That is the entire mechanism. There is no separate inheritance system; a longer chain is inheritance.
Which makes method overriding obvious rather than a rule:
console.log(rex.speak()); // Rex barks
Lookup starts at rex, fails, moves to Dog.prototype, finds speak there, and stops. Animal.prototype.speak is never reached because the search already succeeded. "Overriding" is just a nearer match winning, the same shadowing you saw in Unit 1.
And instanceof reports both, for the reason you now know:
console.log(rex instanceof Dog); // true
console.log(rex instanceof Animal); // true
console.log(rex instanceof Object); // true
All three .prototype objects sit in the chain, and instanceof walks the whole chain.
There is a second link that people miss:
console.log(Object.getPrototypeOf(Dog) === Animal); // true
extends links the two constructor functions as well, not only their prototypes. That second link is what makes static members inherit, which is the next lesson.
Pro Tip: Whenever inheritance behaves unexpectedly, draw the chain. Instance, then each
.prototypefrom the most specific class up to the least, thenObject.prototype, thennull. Every question about which method runs is answered by walking that list from the left and stopping at the first match.
EXERCISE
2super in a Constructor
A subclass constructor has one hard rule, and the reason for it follows directly from how new builds an object.
The rule: call super before you touch this.
class Animal {
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // must come first
this.breed = breed;
}
}
const rex = new Dog("Rex", "collie");
console.log(rex.name, rex.breed); // Rex collie
Break the rule and the error is specific:
class Broken extends Animal {
constructor(name, breed) {
this.breed = breed; // ReferenceError
super(name);
}
}
// ReferenceError: Must call super constructor in derived class
// before accessing 'this' or returning from derived constructor
The reason is worth understanding rather than memorising. In a derived class, this does not exist yet when the constructor starts. The parent constructor is what creates it. super(name) runs Animal's constructor, which produces the object, and only then does this become available to the subclass. Before that line there is genuinely nothing to assign to.
That is a real difference from the base case. In a class with no extends, new creates the object and this is ready on line one, exactly as in Unit 1.
Omit the constructor entirely and one is supplied for you:
class Dog extends Animal {
speak() {
return `${this.name} barks`;
}
}
// Behaves as though you had written:
// constructor(...args) { super(...args); }
console.log(new Dog("Rex").name); // Rex
This is why the first example worked without a constructor. If you only add methods, you do not need to write one.
A subclass that forgets super altogether fails even with no this:
class NoSuper extends Animal {
constructor() {
// nothing at all
}
}
// new NoSuper();
// ReferenceError: Must call super constructor in derived class before
// accessing 'this' or returning from derived constructor
Returning from a derived constructor without having called super is an error in itself, because the object was never made.
Pro Tip: Read
super(...)as "build the part of this object that the parent is responsible for". Once you hear it that way, the ordering rule stops being arbitrary: you cannot decorate an object before it exists, and the parent is what brings it into existence.
EXERCISE
3super in a Method, and What It Is Not
Inside a method, super reaches the parent's version of that method, and it resolves in a way that is not what most people assume.
Extending behaviour rather than replacing it:
class Animal {
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
speak() {
return `${super.speak()} (specifically, a bark)`;
}
}
const rex = new Dog();
rex.name = "Rex";
console.log(rex.speak());
// Rex makes a sound (specifically, a bark)
super.speak() calls Animal.prototype.speak while leaving this pointing at rex. That is why this.name inside the parent method still resolves to "Rex". The method came from the parent; the object did not change.
What super is not: it is not this.__proto__.
// A tempting but wrong mental model:
// super.speak() === Object.getPrototypeOf(this).speak.call(this)
// For one level it happens to agree. Add a level and it breaks:
class A {
who() {
return "A";
}
}
class B extends A {
who() {
return `B -> ${super.who()}`;
}
}
class C extends B {
who() {
return `C -> ${super.who()}`;
}
}
console.log(new C().who()); // C -> B -> A
If super meant "the prototype of this", then inside B.who the value of this is a C, so Object.getPrototypeOf(this) would be C.prototype, and B.who would call itself forever. It does not, because super is resolved from where the method was defined, not from what this currently is. Each method's super is fixed to its own class's parent when the class is created.
That is also why super only works inside a method shorthand, and not in a function assigned to a property:
class Broken extends A {
// who: function () { return super.who(); }
// SyntaxError: 'super' keyword unexpected here
}
The shorthand form records which object the method belongs to. A plain function assignment does not, so there is nothing for super to resolve against.
And a pattern you will use often:
class Base {
toJSON() {
return { id: this.id };
}
}
class Post extends Base {
toJSON() {
return { ...super.toJSON(), title: this.title };
}
}
const p = new Post();
p.id = 1;
p.title = "Hello";
console.log(p.toJSON()); // { id: 1, title: 'Hello' }
Each level contributes its own fields and delegates the rest upward, so no level has to know what the others hold.
super.method() means "the version of this method one level up from where I am written, called on the object I am currently working with". Both halves matter. The first half is why deep chains do not loop; the second is why the parent's method still sees the subclass's data.
