Can JavaScript classes/objects have constructors? How are they created?
In JavaScript the invocation type defines the behaviour of the function:
func()
obj.func()
new func()
func.call()
or func.apply()
The function is invoked as a constructor when calling using new
operator:
function Cat(name) {
this.name = name;
}
Cat.prototype.getName = function() {
return this.name;
}
var myCat = new Cat('Sweet'); // Cat function invoked as a constructor
Any instance or prototype object in JavaScript have a property constructor
, which refers to the constructor function.
Cat.prototype.constructor === Cat // => true
myCat.constructor === Cat // => true
Check this post about constructor property.