Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this object 'see' its inherited properties?

Tags:

javascript

I've just discovered __proto__ is not a property of an object. It is an accessor property of Object.prototype (source). Chrome's console definitely confused me :/.

So when we see something like:

enter image description here

And we do something like this:

o = {}; o.valueOf()

What is happening step-by-step? I'm not quite sure what role Object.prototype.__proto__ has to play now and if it helps in any way.

I am re-reading MDN documentation and articles I've saved but I would greatly appreciate a step-by-step explanation in the case of my o example, in the mean-time.

My guess:

I know that Object.prototype.__proto__ is an accessor property that will return a 'special, hidden' [[prototype]] 'internal slot'/property.

In the case of o = {}; o.valueOf(), I suspect o somehow has the ability to access Object.prototype.__proto__ which will return/reference Object.prototype. This doesn't make sense to me at all (if you can see Object.prototype.__proto__ why not just see Object.prototype so I'm sure it's not right.

like image 263
tonitone120 Avatar asked Aug 07 '20 19:08

tonitone120


1 Answers

What is happening step-by-step? I'm not quite sure what role Object.prototype.__proto__ has to play now.

The .__proto__ accessor on Object.prototype plays absolutely no role in the property access. You're not using it explicitly, and you shouldn't do.

When you access o.valueOf, the engine first checks whether the object o has an own valueOf property. It doesn't in your case. Then it goes to the prototype chain, i.e. the engine does access the internal [[prototype]] slot to find Object.prototype, which o is inheriting from. This object does have a valueOf property, so the engine does access it and use the function value it is holding. The result of the property access is then called.

The engine can directly access the internal slot, it doesn't need to use any language-level entity. In the same way, the devtools debugger, the Object.getPrototypeOf function or the .__proto__ getter can access these internal data structures, as that's how the engine implemented them to work.

like image 184
Bergi Avatar answered Oct 25 '22 07:10

Bergi