The Super Keyword in JavaScript Subclassing
In JavaScript subclassing, the super keyword is used to
access and call functions on an object’s parent class. It serves two
primary purposes: invoking the parent class’s constructor and calling
methods defined on the parent class’s prototype. Understanding how and
when to use super is essential for properly implementing
class inheritance and managing object states in modern JavaScript
(ES6+).
1. Calling the Parent Constructor
When creating a subclass using the extends keyword, the
derived class must call super() inside its
constructor before accessing the this keyword.
Invoking super() executes the parent class constructor,
properly initializing the inherited properties and binding the instance
to this.
class Animal {
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // Calls the Animal constructor
this.breed = breed;
}
}
const myDog = new Dog("Buddy", "Golden Retriever");
console.log(myDog.name); // "Buddy"If you attempt to use this before calling
super(), JavaScript will throw a
ReferenceError.
2. Accessing Parent Methods
The super keyword allows a subclass to call methods from
its parent class. This is particularly useful when overriding a method
in the subclass while still retaining the original functionality of the
parent implementation.
class Animal {
speak() {
return `${this.name} makes a noise.`;
}
}
class Dog extends Animal {
speak() {
// Calls the parent speak() method and appends new behavior
return `${super.speak()} Specifically, it barks.`;
}
}
const dog = new Dog("Buddy");
console.log(dog.speak()); // "Buddy makes a noise. Specifically, it barks."3. Calling Static Methods
The super keyword is not limited to instance methods; it
also works within static methods to invoke static methods
on the parent class.
class Parent {
static identify() {
return "Parent class";
}
}
class Child extends Parent {
static identify() {
return `${super.identify()} extended by Child class`;
}
}
console.log(Child.identify()); // "Parent class extended by Child class"Key Rules to Remember
- Constructor Requirement: In a derived class
constructor,
super()must be called before usingthis. - Scope:
superrefers to the prototype of the current class when used in methods, and the parent constructor when called as a function (super()). - Validity:
supercan only be used inside classes or object literals with concise method syntax.