Home >>Javascript Tutorial >JavaScript Constructor Method

JavaScript Constructor Method

Constructor method in JavaScript

A JavaScript constructor method is basically a distinctive type of method that is used to initialize and create an object and is called whenever a memory is allocated for an object.

Please note these are some points that should be kept in mind:

  • In order to declare a constructor method, constructor keyword is used.
  • The class can only have one constructor method.
  • Use of parent class constructor through super keyword is allowed by the JavaScript.

Examples of Constructor Methods

Example 1. Here is an example of constructor method

<script>  
class Employee 
{  
  constructor() 
  {  
    this.id=11;  
    this.name = "Sonu Chowdhary";  
  }   
}  
var emp = new Employee();  
document.writeln(emp.id+" "+emp.name);  
</script>  
Output :11 Sonu Chowdhary

Constructor Method Example: super keyword

2. Here is an example for the constructor method including super keyword:

<script>  
class CompanyName  
{  
  constructor()  
  {  
    this.company="Phptpoint";  
  }  
}  
class Employee extends CompanyName {  
  constructor(id,name) {  
   super();  
    this.id=id;  
    this.name=name;  
  }   
}     
var emp = new Employee(5,"Sonu");  
document.writeln(emp.id+" "+emp.name+" "+emp.company);  
</script> 
Output :5 Sonu Phptpoint

No Sidebar ads