Are you baffled by the new operator in JavaScript? Wonder what the difference between a function and a constructor is? Or what the heck a prototype is used for?
WHAT IS A CONSTRUCTOR?
A constructor is any function which is used as a constructor. The language doesn’t make a distinction. A function can be written to be used as a constructor or to be called as a normal function, or to be used either way.
A constructor is used with the new keyword:
var Vehicle = function Vehicle() {
// ...
}
var vehicle = new Vehicle();
WHAT HAPPENS WHEN A CONSTRUCTOR IS CALLED?
When new Vehicle()
is called, JavaScript does four things:
It creates a new object.
It sets the constructor property of the object to Vehicle.
It sets up the object to delegate to Vehicle.prototype.
It calls Vehicle() in the context of the new object.
The result of new Vehicle() is this new object.
1. IT CREATES THE NEW OBJECT.
This is nothing special, just a fresh,
new object: {}
.
2. IT SETS THE CONSTRUCTOR PROPERTY OF THE OBJECT TO VEHICLE.
This means two things:
vehicle.constructor == Vehicle // true
vehicle instanceof Vehicle // true
This isn’t an ordinary property. It won’t show up if you enumerate the properties of the object. Also, you can try to set constructor, but you’ll just set a normal property on top of this special one. To wit:
vehicle; // {}
var FuzzyBear = function FuzzyBear() { };
vehicle.constructor = FuzzyBear;
vehicle; // { constructor: function FuzzyBear() }
vehicle.constructor == FuzzyBear; // true
vehicle instanceof FuzzyBear // false
vehicle instanceof Vehicle // true
The underlying, built in constructor property is something you can’t set manually. It can only be set for you, as part of construction with the new
keyword.
3. IT SETS UP THE OBJECT TO DELEGATE TO VEHICLE.PROTOTYPE.
Now it gets interesting.
A function is just a special kind of object, and like any object a function can have properties. Functions automatically get a property called prototype, which is just an empty object. This object gets some special treatment.
When an object is constructed, it inherits all of the properties of its constructor’s prototype. I know, it’s a brainful. Here.
Vehicle.prototype.wheelCount = 4;
var vehicle = new Vehicle;
vehicle.wheelCount; // 4
YOU SAID A MOUTHFUL.
The JavaScript prototype chain is a little different than how most languages work, so it can be tricky understand. It doesn’t make it any easier when JavaScript gets syntax that makes it looks more like other languages, like inheriting Java’s new operator. But if you know what you’re doing, you can do some crazy-cool things with it.