Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why inherited objects members are accessible by key but 'hidden'?

While playing with JavaScript (which is pretty new for me), I found some strange behaviour:

var some_object = {
    foo: "bar",
    baz: "moo"
};

console.log(some_object); // { foo: 'bar', baz: 'moo' }

var inherited_object = Object.create(some_object);
console.log(inherited_object); // {} 
console.log(inherited_object.baz); // moo

Inherited object looks 'empty' but its members are still accessible by key. What is going on here and what logic stands behind such behaviour?

like image 257
Igor Pomaranskiy Avatar asked Dec 24 '22 13:12

Igor Pomaranskiy


2 Answers

This is how prototypal inheritance works.

When you use Object.create to create a new object from existing object, the properties are inherited from the object from which the object is being created. So, the object that is newly created may look empty but contains reference to the inherited properties from parent.

The inherited object's reference is stored in the __proto__ link of the object which contains reference to the parent object properties.

When you access a non-existing property on object, it's prototype is searched for the property, if not found its parent is searched until the grandparent Object. If the property is not found in Object then error/message is returned.

_____________              _____________              ______________
|Own Members|       -----> |     foo    |          -->| toString() |
|           |       |      |     bar    |          |  |  valueOf() |
|           |       |      |            |          |  |            |
|___________|       |      |____________|          |  |            |
| __proto__ |-------|      |  __proto__ |-----...--   |            |
-------------              --------------             --------------

inherited_obj              some_obj                       Object

Notice that the all the objects except Object has prototype link.

The prototype chain is not hidden, you can see that if you log it, inside the __proto__ property.

like image 105
Tushar Avatar answered Dec 27 '22 02:12

Tushar


That's Javascript's prototype chain. Whenever you access a property on an object, Javascript first checks if the actual object has that property, and if not checks if the object's prototype has that property, and if not if that object's prototype has that property and so on...

console.log limits itself to the "first level" of properties in direct outputs, but in modern Javascript consoles you can typically click and expand the object's __proto__ to traverse up the chain.

like image 27
deceze Avatar answered Dec 27 '22 03:12

deceze