The Super Keyword
When working with inherited classes, you will often need to reference the parent class directly. The super keyword allows you to call methods (including the constructor) belonging to an object’s parent.
Calling the Parent Constructor
If a child class needs to initialize its own unique properties, it must have its own constructor(). However, before it can use the this keyword to set its own properties, it is strictly required to call super() to trigger the parent class’s constructor first.
class Titan {
constructor(name) {
this.name = name;
}
}
class BeastTitan extends Titan {
constructor(name, power) {
// 1. Call the parent's constructor first
super(name);
// 2. Now you can set child-specific properties
this.power = power;
}
}
const beast = new BeastTitan("Zeke", 9000);
console.log(beast.name); // "Zeke"
console.log(beast.power); // 9000
Calling Parent Methods
Sometimes you want to override a parent method, but you don’t want to completely discard its original logic. You can use super.methodName() to execute the parent’s version of the method, and then append your own custom behavior to the result.
class Titan {
constructor(name) {
this.name = name;
}
toString() {
return `Titan - Name: ${this.name}`;
}
}
class BeastTitan extends Titan {
constructor(name, power) {
super(name);
this.power = power;
}
toString() {
// Call the parent's toString(), and concatenate the power level to it
return `${super.toString()}, Power: ${this.power}`;
}
}
const beast = new BeastTitan("Zeke", 9000);
console.log(beast.toString());
// Output: Titan - Name: Zeke, Power: 9000