The super keyword in JavaScript is used to access and call functions on an object's parent class. It is primarily used within class inheritance to call methods or constructors from the superclass.

💡 What is super?
super allows a subclass to access properties and methods of its parent class, enabling code reuse and method extension.
Using super in a constructor
When extending a class, you must call super() inside the subclass constructor before using this. This calls the parent class constructor.
📌 Deep Dive: Calling Parent Constructor
class Animal {
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // Call parent constructor
this.breed = breed;
}
}
const myDog = new Dog('Max', 'Golden Retriever');
console.log(myDog.name); // Output: Max
console.log(myDog.breed); // Output: Golden Retriever
Golden Retriever
Using super to call parent methods
Within subclass methods, super.methodName() calls the parent class method, allowing you to extend or customize behavior.
📌 Deep Dive: Calling Parent Methods
class Animal {
speak() {
return 'Animal makes a sound';
}
}
class Dog extends Animal {
speak() {
const parentSound = super.speak(); // Call parent method
return parentSound + ' and Dog barks';
}
}
const myDog = new Dog();
console.log(myDog.speak()); // Output: Animal makes a sound and Dog barks
⚠️ Important Usage Note
You must call super() before accessing this in a subclass constructor. Omitting it causes a ReferenceError.
super Usage| Context | Purpose |
|---|---|
| Constructor | Call parent class constructor to initialize inherited properties |
| Methods | Call parent class methods to extend or reuse behavior |
Key points to remember:
super()calls the parent constructor.super.method()calls a method from the parent class.- Use
superonly in classes that extend another class. - Always call
super()before usingthisin constructors.
💡 Why use super?
It enables subclasses to build upon and reuse the functionality of their parent classes, promoting cleaner and more maintainable code.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Where must you call super() in a subclass constructor?
Question 2 of 2
How do you call a method named greet from the parent class inside a subclass method?
Loading results...