How to call the constructor of a parent class in JavaScript?

In this article, we are going to explore constructors in an object. We can create inheritance in terms of object, i.e. a parent object can have one or multiple child objects. Now we can call the constructors of a parent object from the child object.

Constructor

These are the instances of a class that is commonly referred to as an Object. The new keyword from JavaScript uses a constructor to be called when an object needs to be declared or created. We can set properties into an object using these constructors.

Inheritance in JavaScript

This is the ability of an object to access the properties or methods of another object. This ability is known as Inheritance. Objects can inherit properties and methods from the parent Objects. And the child objects can extend the parent properties.

For calling the constructor of a parent class we can use the super keyword. The super() method from the constructor method is used for the invocation of the constructor method of the parent class to get access to the parent’s properties and methods.

Example 1

In the below example, we have created 2 classes i.e. parent and the child class. The child class extends the parent class. Now for calling the constructor from the parent class we will use the super() method that will be responsible for calling this constructor and executing the actions necessary.

# index.html



   Property Descriptors


   

      Welcome To Tutorials Point    

   

Output

On successful execution of the above program you will find the result in the console similar as below screenshot

Example 2

In the below example, we are calling the instance of the base class from the child class. Since the instance created is of base class the method for child class will not be called.

# index.html



   Property Descriptors


   

      Welcome To Tutorials Point    

   

Output


Updated on: 2022-04-22T12:46:27+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements