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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With