How do the extends keyword and the super keyword work?
The extends keyword sets up the prototype link between a class and its parent. The class becomes the parent prototype, and the parent constructor becomes the parent of the class constructor, so the chain continues upwards.
class Shape {
constructor(sides) {
this.sides = sides;
}
describe() {
return `a shape with ${this.sides} sides`;
}
}
class Square extends Shape {
constructor(size) {
super(4); // call the parent constructor first
this.size = size;
}
describe() {
return `a square of ${this.size}`;
}
}
const square = new Square(10);
console.log(square.describe()); // "a square of 10"
console.log(square.sides); // 4
console.log(square instanceof Shape); // trueThe super keyword has two jobs. Inside a constructor, calling super passes the arguments to the parent constructor and runs it. Inside a method, super.method() calls the parent version of that method with the same receiver, which is how you extend a method rather than replace it.
The order matters. The parent constructor has to run before the child constructor's own body, because the parent sets up state that the child may rely on. In the example, the parent sets sides and the child then reads it when it overrides describe.
There is a subtlety with super in a method. The parent method is looked up on the prototype of the home object at the moment the method runs, and it is called with the current this. That is why super.describe() inside a method of a derived class finds the parent implementation rather than looping back to itself.