I cannot find anywhere in the JS spec where functions – when called with new should set the constructor property of their prototype to themselves.
Sure the spec says the Built-in constructors (Object, Array, String, &c) all set their prototype.constructor properties to themselves (i.e. Object.prototype.constructor = Object) BUT I can’t find anywhere that says this must/should happen for other constructors (seems it should be spelled out in the [[Construct]] section (13.2.2 [[Construct]]) yet it is not:
function F() {};
var obj = new F();
Object.getPrototypeOf(obj).constructor == F; // non-standard?? I can't find where in spec
I ask because I see a lot of code ‘resetting’ the prototype.constructor property of a constructor ‘back’ to itself – yet this appears to be non-standard that this property points back to the constructor function in the first place?
function F() {};
F.prototype = new Parent();
F.prototype.constructor = F; // 'reset' it cuz it changed! (according to spec it should never have been set? Except in Object.prototype.
Can/should JS programmers rely on this non-standard(?) expectation that a constructor’s prototype.constructor property will point back to the constructor function itself if the prototype property is not set?
V8 certainly does this:
function F() {};
console.log(F.prototype.constructor === F); // true! WHY??? not in spec? Should be Object?
Hope that made vague sense – thanks!!
Mark
PS Due to their mutability I would only rely on instanceof instead of using the constructor property.
It is standard for all functions to have a
.prototypeproperty that points to an object with a.constructorproperty that points back to the function.13.2 Creating Function objects
So you can see
Fis the new function andprotois the prototype object. Theprotogets a"constructor"property that points toF, andFgets a"prototype"property that points to theprotoobject