Search code examples
javascriptprototype-oriented

Prototype chain can't get Object()?


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?


Solution

  • In JS OOP the constructor and prototype properties 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 the Object top-level prototype, since when you have function a(){} the right constructor and prototype properties aren't set on a. I can't even manage to coerce them onto a; in Chrome I get:

    > function a(){}
    undefined
    > a.constructor.prototype
    function Empty() {}
    > a.constructor.prototype = Object.prototype
    Object
    > a.constructor.prototype
    function Empty() {} // hmmmm, the assignment didn't take...
    

    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.prototype you use .__proto__:

    function a(){}
    b = new a();
    b.__proto__ === Object.prototype; // false
    b.__proto__.__proto__ === Object.prototype; // true since we reached the top of the prototype chain
    

    It is important to note that the property __proto__ has never been standard and in ES5 was standardised in a slightly different manner:

    obj.__proto__ === Object.getPrototypeOf(obj);
    

    This renders .__proto__ deprecated.