Sobes.tech
Senior

Tell me about the super() function and when you use it?

sobes.tech AI

Answer from AI

The super() function is used in classes to call the constructor of the parent class or parent methods.

It is used in two main cases:

  1. In the constructor of a child class to call the constructor of the base class and properly initialize inherited properties.

  2. To call parent methods when you need to extend or override behavior but want to preserve some of the base class logic.

Example:

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

class Dog extends Animal {
  constructor(name, breed) {
    super(name); // call the constructor of Animal
    this.breed = breed;
  }
  speak() {
    super.speak(); // call the speak method from Animal
    console.log(`${this.name} barks.`);
  }
}

Without calling super() in the constructor of the child class, there will be an error because the base class is not initialized.