In JavaScript, all normally-created functions have a prototype
property which is, initially, an object created by the JavaScript engine with one property: constructor
, which refers back to the function. So for
function A() {
}
...we know that, initially, A.prototype.constructor === A
. This also means that objects created via new A
will inherit constructor
, and so:
var o = new A();
console.log(o.constructor === A); // true
But if you replace the object on the prototype
property with something else, as your code snippet does, then the new thing's constructor
property (which it inherits) is pointing to the wrong function unless you fix it:
function A() {
}
A.prototype = {}; // Replace the object
var o = new A();
console.log(o.constructor === A); // false
console.log(o.constructor === Object); // true
Oops. That's why the snippet you've quoted is setting constructor
on the object it's assigning to A.prototype
.
But what's the point of the constructor
property? Actually, nothing in the JavaScript specification ever uses that property; the only mention of it relates to the above, making sure that the initial object on the prototype
property has constructor
referring back to the function.
But some code (including some libraries) may assume that constructor
is set "properly" (e.g., the way it is by default by the JavaScript engine), and may try to use it to figure out what an object "is" (although there's usually little if any reason to do that; in the rare case when you actually care, instanceof
is usually the better way to check, as it allows for derived objects). Or they may try to use it in cloning operations, although as of ES5 there are better ways.
In any case, since there is (rare) code out there that may rely on the constructor
property being set as it is by the JavaScript engine, well-behaved code replacing the prototype
property entirely sets constructor
the same way the JavaScript engine does, just in case.
In practice, it's very common for people to leave out that step when replacing the object on the prototype
property, and so relying on constructor
in new code is not best practice. But being sure you set constructor
properly probably still is, just in case.