The constructor method is a special method for creating and initialising an object created within a class. When it comes to JS the syntax is slightly different as you can see in the example snippet below
class Task {
constructor(name) {
this.name = name;
this.completed = false;
}
complete() {
console.log("Completing task " + this.name);
}
save() {
console.log("Saving task " + this.name);
}
}
var task1 = new Task("task1");
task1.save(); //output: Saving task task1
task1.complete(); //output: Completing task task1
If one runs the above code through a transpiler like
Babel for browser compatibility, the following code would be generated.
Also notice that creating methods inside the Task function is a bad idea as it creates replication of method each time an instance is created.
var Task = function(name) {
this.name = name;
this.completed = false;
this.save = function() {
console.log(
"Not a good idea as it replicates the method among all instances"
);
};
};
Task.prototype.save = function() {
console.log("Saving task " + this.name);
};
Task.prototype.complete = function() {
console.log("Completing task " + this.name);
};
var task1 = new Task("task1");
task1.save(); //output: Saving task task1
task1.complete(); //output: Completing task task1
Hope this clears some of the doubts on Constructor.
p.s : Constructor has been added post EcmaScript 2015.