How to Use super in JavaScript: Syntax and Examples
In JavaScript,
super is used inside a subclass to call methods or constructors from its parent class. You use super() to call the parent constructor and super.methodName() to call a parent method.Syntax
The super keyword is used in two main ways inside a subclass:
- Calling the parent constructor: Use
super()inside the subclass constructor to run the parent class constructor. - Calling a parent method: Use
super.methodName()to invoke a method defined in the parent class.
javascript
class Parent { constructor(name) { this.name = name; } greet() { return `Hello, ${this.name}`; } } class Child extends Parent { constructor(name, age) { super(name); // calls Parent constructor this.age = age; } greet() { return super.greet() + `, you are ${this.age} years old.`; // calls Parent greet method } }
Example
This example shows how super() calls the parent constructor and super.greet() calls the parent method to extend its behavior.
javascript
class Animal { constructor(name) { this.name = name; } speak() { return `${this.name} makes a sound.`; } } class Dog extends Animal { constructor(name, breed) { super(name); // call Animal constructor this.breed = breed; } speak() { return super.speak() + ` It is a ${this.breed}.`; } } const dog = new Dog('Buddy', 'Golden Retriever'); console.log(dog.speak());
Output
Buddy makes a sound. It is a Golden Retriever.
Common Pitfalls
Common mistakes when using super include:
- Forgetting to call
super()in the subclass constructor before usingthis. This causes a ReferenceError. - Using
superoutside of subclass methods or constructors, which is not allowed. - Not matching the parent constructor parameters when calling
super().
javascript
class Parent { constructor(name) { this.name = name; } } // Wrong: Using this before super() class Child extends Parent { constructor(name) { // this.age = 10; // Error: Must call super() first super(name); this.age = 10; } } // Correct way class ChildCorrect extends Parent { constructor(name) { super(name); // call parent constructor first this.age = 10; } }
Quick Reference
super()- Call parent class constructor inside subclass constructor.super.method()- Call a method from the parent class.- Always call
super()before usingthisin subclass constructor. supercan only be used in subclass methods or constructors.
Key Takeaways
Use
super() in subclass constructors to call the parent constructor before accessing this.Call parent class methods inside subclass methods with
super.methodName().Never use
super outside subclass methods or constructors.Match the parent constructor parameters when calling
super().Forgetting to call
super() first in subclass constructor causes errors.