This figure again shows that every object has a prototype. Constructor function Foo also has its own
__proto__
which is Function.prototype, a
I've made for myself a small drawing that represents the following code snippet:
var Cat = function() {}
var tom = new Cat()
I have a classical OO background, so it was helpful to represent the hierarchy in this manner. To help you read this diagram, treat the rectangles in the image as JavaScript objects. And yes, functions are also objects. ;)
Objects in JavaScript have properties and __proto__
is just one of them.
The idea behind this property is to point to the ancestor object in the (inheritance) hierarchy.
The root object in JavaScript is Object.prototype
and all other objects are descendants of this one. The __proto__
property of the root object is null
, which represents the end of inheritance chain.
You'll notice that prototype
is a property of functions. Cat
is a function, but also Function
and Object
are (native) functions. tom
is not a function, thus it does not have this property.
The idea behind this property is to point to an object which will be used in the construction, i.e. when you call the new
operator on that function.
Note that prototype objects (yellow rectangles) have another property called
constructor
which points back to the respective function object. For brevity reasons this was not depicted.
Indeed, when we create the tom
object with new Cat()
, the created object will have the __proto__
property set to the prototype
object of the constructor function.
In the end, let us play with this diagram a bit. The following statements are true:
tom.__proto__
property points to the same object as Cat.prototype
.
Cat.__proto__
points to the Function.prototype
object, just like Function.__proto__
and Object.__proto__
do.
Cat.prototype.__proto__
and tom.__proto__.__proto__
point to the same object and that is Object.prototype
.
Cheers!