Loading

Constructor method

  • In JavaScript, a constructor method is used to create and initialize objects.
  • In object-oriented programming, Constructors are used to define and create objects of a particular class or type. 
  • They are called when you use the new keyword to create an instance of an object.

Syntax:

function ClassName(param1, param2, ...) {
 // Constructor code here
 // Initialize instance properties
 this.param1 = param1;
 this.param2 = param2;
 // ...
}
  • ClassName is the name of the constructor function.
  • param1, and param2, are parameters that you can pass to the constructor when creating an instance of the object.
  • this refers to the newly created instance of the object, and you can use it to set instance properties.

Example:

<!DOCTYPE html>
<html>

<body>

  <script>
    class Employee {
      constructor() {
        this.id = 105;
        this.name = "john";
      }
    }
    var emp = new Employee();
    document.writeln(emp.id + " " + emp.name);
  </script>

</body>

</html>

Output:

105  john


Using super keyword:

  • super keyword is used to call parent class Constructor.

Example:

<!DOCTYPE html>
<html>

<body>

  <script>
    class CompanyName {
      constructor() {
        this.company = "Quipoin";
      }
    }
    class Employee extends CompanyName {
      constructor(id, name) {
        super();
        this.id = id;
        this.name = name;
      }
    }
    var emp = new Employee(1, "John");
    document.writeln(emp.id + " " + emp.name + " " + emp.company);
  </script>

</body>

</html>

Output:

1 John Quipoin