Why is __proto__ undefined?

When reading on Javascript prototypes, I came across a behavior that I cannot explain. I am testing this in the chrome console (this is V8).

var fruit = {taste:'good'}; var banana = Object.create(fruit); console.log(banana.taste); //"good" console.log(banana.__proto__); //Object {taste: "good"} console.log(Object.getPrototypeOf(banana)); //Object {taste: "good"} 

So far, everything is as expected. However, if I do this:

 var drink = Object.create(null); Object.defineProperty(drink, 'taste', {value:"nice"}); var coke = Object.create(drink); console.log(coke.taste); //"nice" console.log(coke.__proto__); //undefined console.log(Object.getPrototypeOf(coke)); //Object {taste: "nice"} 

then coke.__proto__ === undefined . Why is the second case undefined ?

+8
javascript prototype v8
source share
1 answer

I once discovered a problem for this behavior , but was closed as standards-compliant behavior. Due to the problem:

This works as directed. ES6 __proto__ is a getter defined in Object.prototype. For an object that does not have this in its prototype chain, it is unavailable (as, for example, hasOwnProperty is not). Instead, you need to use Object.getPrototypeOf.

This is true: The ES6 B.2.2.1 section defines Object.prototype.__proto__ ; therefore, the __proto__ property inherits from Object.prototype . However, your coke object was created using Object.create(null) , so it does not have Object.prototype in its prototype chain.

An object always has internal knowledge for its prototype, stored in the [[Prototype]] internal slot . The __proto__ property is a way to access this internal prototype using code. The lack of a __proto__ object __proto__ not affect its [[Prototype]] slot, which still exists.

Clearly: coke has a prototype (stored in [[Prototype]]), and this prototype is a drink object. You can see this with Object.getPrototypeOf(coke) . However, this is a whole chain of prototypes, as the drink prototype is null . Therefore, coke cannot inherit __proto__ from Object.prototype.__proto__ , because in the prototype chain it does not have Object.prototype .

+7
source share

All Articles