Skip to content

JavaScript super constructor

  • by

In JavaScript, the super keyword is used to call the parent class’s constructor, but JavaScript itself does not have a built-in “super constructor” concept.

super(arguments);

In JavaScript, the super keyword is used to call the constructor of a parent class within the constructor of a child class. This allows you to initialize the inherited properties and behavior defined in the parent class before adding any additional functionality specific to the child class.

JavaScript super constructor example

Simple example code that demonstrates the usage of the super keyword to call the parent class constructor in JavaScript:

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

  sayHello() {
    console.log(`Hello, I'm ${this.name}.`);
  }
}

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

  bark() {
    console.log("Woof!");
  }
}

const dog = new Dog("Buddy", "Golden Retriever");
dog.sayHello();
dog.bark();     
console.log(dog.name); 
console.log(dog.breed);

Output:

JavaScript super constructor

In this example, we have a parent class Animal with a constructor that accepts a name parameter. The Dog class extends Animal and has its own constructor that takes a name and breed parameter.

Inside the Dog class constructor, super(name) is called to invoke the Animal class constructor with the name argument. This initializes the name property inherited from Animal. Then, the breed property specific to the Dog class is assigned.

When creating a new instance of Dog with new Dog("Buddy", "Golden Retriever"), the name and breed values are passed to the respective parameters in the Dog constructor. The sayHello method inherited from the Animal class and the bark method defined in the Dog class can be called on the dog object.

By using super to call the parent class constructor, you can properly initialize inherited properties and utilize the functionality of the parent class in the child class.

Do comment if you have any doubts or suggetions on this Js constructor topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *