Sunday, September 22, 2019

JavaScript Constructor Method

A JavaScript constructor method is a special type of method which is used to initialize and create an object. It is called when memory is allocated for 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 see a simple example of a constructor method.
  1. <script>  
  2. class Employee {  
  3.   constructor() {  
  4.     this.id=101;  
  5.     this.name = "Martin Roy";  
  6.   }   
  7. }  
  8. var emp = new Employee();  
  9. document.writeln(emp.id+" "+emp.name);  
  10. </script>  

Output:
101 Martin Roy

Constructor Method Example: super keyword

The super keyword is used to call the parent class constructor. Let's see an example.
  1. <script>  
  2. class CompanyName  
  3. {  
  4.   constructor()  
  5.   {  
  6.     this.company="Javatpoint";  
  7.   }  
  8. }  
  9. class Employee extends CompanyName {  
  10.   constructor(id,name) {  
  11.    super();  
  12.     this.id=id;  
  13.     this.name=name;  
  14.   }   
  15. }     
  16. var emp = new Employee(1,"John");  
  17. document.writeln(emp.id+" "+emp.name+" "+emp.company);  
  18. </script>  

Output:
1 John Javatpoint

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

No comments:

Post a Comment