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 parent becomes the prototype of the child class, and the parent constructor becomes the parent of the child constructor, so the chain continues upwards. The super keyword is the way that a child class calls the parent version of something.
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); // true
The super keyword has two jobs. Inside a constructor, calling super passes the arguments to the parent constructor and runs it. Inside a method, calling super.method() runs the parent version of that method with the same object, and that is how you extend a method instead of replacing it.
The order matters here. The parent constructor has to run before the body of the child constructor, because the parent sets up the state that the child may rely on. In the example above, the parent sets the number of sides, and the child then reads that value when it overrides the describe method.
There is one subtlety with super inside a method. The parent method is looked up on the prototype of the object that the method belongs to, at the moment the method runs, and it is called with the current this. That is why super.describe() inside a method of a child class finds the parent implementation instead of going round in a circle back to itself.