Monday, 10 February 2025

Super keyword in JavaScript

The super keyword is used to call the constructor or methods of the parent class.

super.js 

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name); // Calls the parent class constructor
    this.breed = breed;
  }

  speak() {
    super.speak(); // Calls the parent class method
    console.log(`${this.name} is a ${this.breed} and barks.`);
  }
}

const dog = new Dog('Jimbu', 'Labrador');
dog.speak();

Output

Jimbu makes a sound.
Jimbu is a Labrador and barks.

 

super(name)

super(name) is used in the Dog constructor to call the parent class (Animal) constructor. By calling super(name), the name property is initialized using the parent class's constructor. Without this call, the name property wouldn't be properly set, as it belongs to the parent class.

 

super.speak()

In the speak method of the Dog class, super.speak() is used to call the speak method from the parent class (Animal). This allows the Dog class to first execute the behaviour defined in the Animal class (which prints the generic message about the animal making a sound) before adding its own behaviour (printing a message specific to dogs).

 


Previous                                                    Next                                                    Home

No comments:

Post a Comment