What is a constructor method in JavaScript?

JavascriptWeb DevelopmentFront End Technology

The constructor method in JavaScript is used to create and initialize object created within a class. If a constructor method is not added, then a default constructor should be used.

Note − Only one occurrence of a constructor method is allowed in a class. More than one throws an error.

Example

You can try to run the following code to learn how to implement a constructor method

Live Demo

<html>
   <body>
      <script>
         class Department {
            constructor() {
               this.name = "Department";
            }
         }
         class Employee extends Department {
            constructor() {
               super();
            }
         }
         class Company {}
         Object.setPrototypeOf(Employee.prototype, Company.prototype);
         document.write("<br>"+Object.getPrototypeOf(Employee.prototype) === Department.prototype);
         let myInstance = new Employee();
         document.write("<br>"+myInstance.name);
      </script>
   </body>
</html>
raja
Published on 30-Jan-2018 14:47:10
Advertisements