Class constructor in Javascript
A constructor is a special function which used to creating and initializing objects created within a class. It calls automatically when a class is initiated, it must be define inside class with keyword constructor. If not specified in the class JavaScript will adds an invisible and empty constructor in the class. It allows only one constructor function in the class.
Syntax for constructor
 1 class Person {
 2    // constructor function - optional
 3    constructor(<parameters>) {
 4       // initialize local class properties
 5    }
 6 }

Parameterized constructor

A constructor is define with keyword constructor and parameters. A parameters can be used to initialize the properties of the class.
Constructor
 1 // creating class Person
 2 class Person {
 3   // constructor with parameter(s)  
 4   constructor(name, salary) {
 5       this.name = name;
 6       this.salary = salary;
 7   }
 8 }
In the above example, we have define class with name Person which is taking two input parameters name and salary and assigning to the class properties name and salary. An object of class Person is created using keyword new as shown below.
Creating object with parameters
 1 let person = new Person('JavaScript', 1000);

Default constructor with default values

Default constructor with default values
 1 // creating class Item
 2 class Item {
 3   // constructor without parameter(s)  
 4   constructor() {
 5       this.name = "Item";
 6       this.price = 0.0;
 7   }
 8 }
 9 
 10 let item = new Item();
 11 console.log(item.name); // Item
 12 console.log(item.price); // 0
In the above example, a class Item is define with constructor method that initialized value with default values. An object is created using constructor method and access its property that prints default value of its properties.
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us