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.
1 class Person {
2
3 constructor(<parameters>) {
4
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.
1
2 class Person {
3
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
2 class Item {
3
4 constructor() {
5 this.name = "Item";
6 this.price = 0.0;
7 }
8 }
9
10 let item = new Item();
11 console.log(item.name);
12 console.log(item.price);
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.
Related options for your search