I read an article which explains what prototype chain is.
It says that if I try to access an object’s property but it doesn’t have it, javascript engine will try it’s .constructor.propotype. If it doesn’t have it either then try .construtor.propotype.constructor.propotype. Untill it find the built-in Object().
But I test this:
function a() {}
b = new a();
then:
c = b.constructor.prototype
I get an empty a object.
then:
d = c.constructor.prototype
I get an empty a object.
It loops. No matter how many .constructor.prototype I call, it can’t find Object(). What’s wrong? Do I misunderstand the prototype chain?
In JS OOP the
constructorandprototypeproperties are flaky, in that they aren’t set for you when you perform inheritance. You are supposed to manually set/alter them to implement inheritance. See, for example, this tutorial.It looks like the way you’re trying to climb the prototype chain (by traversing through
.constructor.prototype) never really reaches theObjecttop-level prototype, since when you havefunction a(){}the rightconstructorandprototypeproperties aren’t set on a. I can’t even manage to coerce them ontoa; in Chrome I get:Of course the runtime doesn’t need to do this, since it has a reference to the actual prototype of each object. I.e. the language doesn’t do the lookup via
.constructor.prototype, it saves the prototype of each instance internally. So you can see how the lookup chain works if instead of.constructor.prototypeyou use.__proto__:It is important to note that the property
__proto__has never been standard and in ES5 was standardised in a slightly different manner:This renders
.__proto__deprecated.