The Secret __proto__ Link

When you try to access a property that does not exist in the current object, Javascript will lookup for the prototype property.

Create an object called monkey and use it as a prototype when creating objects with the Human() constructor.

var monkey = {
    feeds: 'bananas',
    breathes: 'air'
};
function Human() {}

Human.prototype = monkey;

Now create a developer object and give it some properties.

var developer = new Human(); developer.feeds = 'pizza'; developer.hacks = 'JavaScript';

Now check some of the properties. hacks is a property of the developer object.

developer.hacks

"JavaScript"

feeds could also be found in the object.

developer.feeds

"pizza"

breathes doesn't exist as a property of the developer object, so the prototype is looked up, as if there is a secret link pointing to the prototype object.

developer.breathes

"air"

We got value from the developer object to the prototype object, using constructor as the middleman, so having something like developer.constructor.prototype should point to monkey. But this is not very reliable and can easily be overwritten at any time. You can overwrite it with something that's not even an object and this will not affect the normal functioning of the prototype chain.

Set the constructor property to some string.

developer.constructor = 'junk'

"junk"

It seems like the prototype is now all messed up.

typeof developer.constructor.prototype

"undefined"

But it isn't, because the developer object, breathes property still returns "air".

developer.breathes

"air"

So the secret link to the prototype still exists. The secret link is exposed in browsers as the __proto__(firefox) property.

developer.__proto__

Object feeds=bananas breathes=air

If we change monkey prototype and all instances will inherit the change.

monkey.test = 1
1

developer.test
1

__proto__ is not the same as prototype. __proto__ is a property of the instances, whereas prototype is a property of the constructor functions.

typeof developer.__proto__
"object"

typeof developer.prototype
"undefined"
Note
__proto__ should be used only for learning or debugging purposes.
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +