JavaScript OOPs Constructor Method

A constructor method in JavaScript is a distinct kind of method designed for the purpose of initializing and generating an object. This method is invoked at the moment memory is assigned for the creation of an object.

Points to remember

  • The constructor keyword is used to declare a constructor method.
  • The class can contain one constructor method only.
  • JavaScript allows us to use parent class constructor through super keyword.
  • Constructor Method Example

Let’s examine a straightforward illustration of a constructor method.

Example

<script>

class Employee {

  constructor() {

    this.id=101;

    this.name = "Martin Roy";

  } 

}

var emp = new Employee();

document.writeln(emp.id+" "+emp.name);

</script>

Output:

Output

101 Martin Roy

Constructor Method Example: super keyword

The super keyword serves the purpose of invoking the constructor of the parent class. Let’s examine an example.

Example

<script>

class CompanyName

{

  constructor()

  {

    this.company="Example";

  }

}

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>

Output:

Output

1 John C# Tutorial

Note - If we didn't specify any constructor method, JavaScript use default constructor method.

Input Required

This code uses input(). Please provide values below: