I'm reviewing ECMAScript 5.1 Specification kinda seriously.
And I'm curious if there is a way to tell what the "real constructor function" of an object in ES5. ( not the explicit "constructor" property )
According to the spec, explicit "constructor" property is just a initial back-reference from the byproduct object of a function object to the function object.
(Here, the byproduct is the object which is initially pointed by the function object's explicit "prototype" property.)
So, explicit "constructor" property has nothing to do with the real constructor of an object:
function Foo(name){ this.name = name; }
var foo = new Foo("Brian");
var bar = { a: 10, b: function(){ if(this.name) return this.name; }};
Foo.prototype = bar;
var foo2 = new Foo("John"); // Let me call Foo as "real constructor" of foo2
Here, even though foo2 was created by Foo, since Foo.prototype was pointing to bar at the moment of creation of foo2, so foo2's internal [[Prototype]] gets to point to bar, and we can check this by:
Object.getPrototypeOf(foo2) === bar // true
Since foo2 doesn't have own "constructor" property as usual, so, reading foo2.constructor is actually [[Prototype]] chain lookup, that is, foo2.constructor --> (( foo2.[[Prototype]] )).constructor --> bar.constructor which is Object, not Foo.
You can check this by:
foo2.constructor === Foo // false
foo2.constructor === Object // true
Finally, is there no way to find Foo from the object foo2?
ADD:
I'm talking about ES5. Please do not bring anything engine-dependent or ES6-thingy (e.g. __proto__ )
Foo.prototypeafter you created the object and evenfoo2 instanceof Foowill not work anymore. Just think of the constructor function as a blue print. You use it to create an object but after you created it, there is nothing that prevents you of doing totally different things to both of them.return this, in which case there is absolutely no link back to the function that created it.