A prototype object has a prototype of its own and it continues like that until the object reaches a prototype with null, meaning end of the
Let’s dive right in to the subject!
Let’s look at this code:
From the code above we can say that
Object y inherits the properties of
Object x and
Object z inherits the properties of
Open your browser console and let’s try something. This can be done by using the inspect element option or developer tools in your browser. This will give a better understanding about prototype inheritance and more importantly the concept of prototype shadowing.
You can either copy the snippet of code above or click on the link below and just run it, then open your browser console to inspect the result using this JS Bin.
After doing this, you will find something similar to this or this exact thing, depending on your browser:
The Prototype chain
From the image above we can see that the main
object "z” that we logged into the console, shows the first
Object.Prototype it inherited from
object "y". The
Object.prototype method is simply linking the objects, saying that “Hey!, I inherited the property “a” from the
object "y" and I have already stored the value”. Then it goes down the prototype chain and checks: is the value
null ? If yes, end. If not, continue and look for the other properties I was told to inherit.
Object.prototype method of
object "y" is saying I inherited two properties named “a” and “m”.
Object z already has a property of “a” which is a newer value. So its just going to say “Hey! Thanks for letting me know. I already have a value for a key with the same name “a”. I wouldn’t be needing the value of property “a”. I would just go ahead and add property “m” to the properties of my object since its my inheritance. Thank again!”.
That’s is Property Shadowing!
You may have never heard of property shadowing, now you have and it might help you in an interview, maybe!
Like it? Share. :)