In JavaScript, the Constructor is a special method within a class that is automatically invoked when a new instance of that class is created.
The main purpose of the constructor is to initialize the object with default values or with values provided by the user.
In other words, the constructor sets the initial state of an object at the time of its creation.
If you want to learn more, you can check out
Basic syntax of the constructor
The syntax of a constructor within a class in JavaScript is as follows:
class MyClass {
constructor(parameter1, parameter2) {
// object property initialization
this.property1 = parameter1;
this.property2 = parameter2;
}
}
constructor()
is the special method of the class.parameter1
,parameter2
are parameters that you can pass to the constructor when creating the instance.this.property1
andthis.property2
assign values to the object’s properties.
This constructor initializes the object’s properties with the values of the parameters provided when the new instance is created.
Basic example
Imagine we want to create a class Car
that represents different cars. We want each car to have properties like make
, model
, and year
.
class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
}
const myCar = new Car('Toyota', 'Corolla', 2020);
console.log(myCar);
In this example:
- The class
Car
has a constructor that takes three parameters:make
,model
, andyear
. - When the instance
myCar
is created, the values'Toyota'
,'Corolla'
, and2020
are passed to the constructor. - The constructor assigns these values to the object’s properties, using
this.make
,this.model
, andthis.year
.
The output of the code will be:
Car { make: 'Toyota', model: 'Corolla', year: 2020 }
Default constructor
If we do not define a constructor within a class, JavaScript will create an empty default constructor.
This default constructor does not perform any initialization actions, meaning no properties are assigned directly upon the creation of the object.
class Person {
// No explicit constructor here
}
const person1 = new Person();
console.log(person1); // Person {}
The object person1
is created successfully, but it has no initialized properties since we have not defined a constructor.
Creating instances with classes
Whenever a new object is created using the new
keyword, JavaScript calls the corresponding class constructor to initialize that object.
let person1 = new Person("Juan", 30);
person1.greet(); // Output: "Hello, my name is Juan and I am 30 years old."
The constructor sets the initial properties of the object, and you can use the parameters you pass to the constructor to flexibly configure those properties.
this inside the constructor
Within the constructor, this
refers to the current instance of the class, that is, the object we are creating.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const person1 = new Person('Juan', 25);
person1.greet(); // "Hello, my name is Juan and I am 25 years old."
In this example:
this.name
andthis.age
assign values to the properties of the objectperson1
within the constructor.greet()
is a method of the class that can access those properties throughthis
.
Default value in the constructor
Sometimes, we may not always want the user to pass all parameters when creating an object. In those cases, we can assign default values within the constructor.
class Car {
constructor(make = 'Unknown', model = 'Unknown', year = 2000) {
this.make = make;
this.model = model;
this.year = year;
}
}
const car1 = new Car();
console.log(car1); // Car { make: 'Unknown', model: 'Unknown', year: 2000 }
const car2 = new Car('Ford', 'Mustang', 1969);
console.log(car2); // Car { make: 'Ford', model: 'Mustang', year: 1969 }
In this case:
- If no values are provided for the properties, the constructor assigns default values to
make
,model
, andyear
. - If values are provided, they override the default values.
The constructor and inheritance
In JavaScript, classes can inherit from other classes. When a class inherits from another, the child class’s constructor can call the parent class’s constructor using super()
.
class Vehicle {
constructor(make, model) {
this.make = make;
this.model = model;
}
}
class Car extends Vehicle {
constructor(make, model, year) {
super(make, model); // We call the parent class's constructor (Vehicle)
this.year = year;
}
}
const car1 = new Car('Honda', 'Civic', 2022);
console.log(car1); // Car { make: 'Honda', model: 'Civic', year: 2022 }
In this example:
- The class
Car
extends from the classVehicle
. - The constructor of
Car
callssuper(make, model)
, which invokes the constructor ofVehicle
to initialize themake
andmodel
properties. - Then, the constructor of
Car
adds the propertyyear
.