Search code examples
javascriptinheritanceprototypeprototype-chain

How does __proto__ work when object is created with Object.create(null)


Consider the following javascript code

var a = Object.create(null);
a.foo = 1;
var b = Object.create(a);
console.log(b.foo);  //prints 1
console.log(b.__proto__);  //prints undefined
b.__proto__ = null;
console.log(b.__proto__);  //prints null
console.log(b.foo);  //prints 1

Can anyone explain how object b is accessing the "foo" property of a even after setting b.__proto__ to null? What is the internal link which is used to access the property of a?

I tried searching through SO for possible explanations but couldn't find any explanation for this particular behaviour of Javascript.


Solution

  • Your problem is that you are using the deprecated __proto__ property, which is a getter/setter on Object.prototype - but your objects don't inherit from that, so it's undefined at first and the assignment creates a standard property with the name __proto__.

    Use the proper Object.getPrototypeOf/Object.setPrototypeOf instead and the code will do what you expect:

    var a = Object.create(null);
    a.foo = 1;
    var b = Object.create(a);
    console.log(b.foo); // 1
    console.log(Object.getPrototypeOf(b)); // {foo:1} - a
    Object.setPrototypeOf(b, null);
    console.log(Object.getPrototypeOf(b)); // null
    console.log(b.foo); // undefined