In JavaScript, the super() method is used to call the constructor of a parent class, and it is typically used in a derived class (also known as a subclass or child class) that extends a parent class.
Example 1: Basic usage of super() in a derived class
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
super.speak();
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Rufus');
dog.speak(); // "Rufus makes a noise." "Rufus barks."
Example 2: Passing arguments to the parent constructor
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
class Square extends Rectangle {
constructor(sideLength) {
super(sideLength, sideLength);
}
}
const square = new Square(5);
console.log(square.area()); // 25
Example 3: Calling parent class methods from the derived class
class Person {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`Hello, my name is ${this.name}.`);
}
}
class Student extends Person {
constructor(name, grade) {
super(name);
this.grade = grade;
}
introduce() {
super.sayHello();
console.log(`I'm in grade ${this.grade}.`);
}
}
const student = new Student('Alice', 10);
student.introduce(); // "Hello, my name is Alice." "I'm in grade 10."
Example 4: Using super() in a static method
class Car {
static honk() {
console.log('Beep beep!');
}
}
class SportsCar extends Car {
static honk() {
super.honk();
console.log('Vroom vroom!');
}
}
SportsCar.honk(); // "Beep beep!" "Vroom vroom!"