🥑Use of Super

In JavaScript, the super keyword is used to call the parent class's constructor or a method from the child class. For example, consider the following code:

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

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

class Cat extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }

  speak() {
    console.log(`${this.name} meows.`);
  }
}

const cat = new Cat('Fluffy', 'Siamese');
cat.speak();
// Output: "Fluffy meows."

In this example, the Cat class extends the Animal class and overrides the speak method. The Cat class also has a constructor that accepts a name and a breed parameter. In the Cat constructor, we use the super keyword to call the Animal constructor and pass it the name argument. This sets the name property of the Cat instance to the value of the name argument.

The super keyword can also be used to call a method of the parent class from the child class. For example, we could modify the speak method of the Cat class to call the speak method of the Animal class like this:

class Cat extends Animal {
  // ...

  speak() {
    super.speak();
    console.log(`${this.name} meows.`);
  }
}

This would cause the Cat instance to make both a noise (using the speak method from the Animal class) and meow (using the speak method from the Cat class).

Last updated