This figure again shows that every object has a prototype. Constructor function Foo also has its own
__proto__
which is Function.prototype, a
Prototype property is created when a function is declared.
For instance:
function Person(dob){
this.dob = dob
};
Person.prototype
property is created internally once you declare above function.
Many properties can be added to the Person.prototype which are shared by Person instances created using new Person().
// adds a new method age to the Person.prototype Object.
Person.prototype.age = function(){return date-dob};
It is worth noting that Person.prototype
is an Object
literal by default (it can be changed as required).
Every instance created using new Person()
has a __proto__
property which points to the Person.prototype
. This is the chain that is used to traverse to find a property of a particular object.
var person1 = new Person(somedate);
var person2 = new Person(somedate);
creates 2 instances of Person
, these 2 objects can call age
method of Person.prototype
as person1.age
, person2.age
.
In the above picture from your question, you can see that Foo
is a Function Object
and therefore it has a __proto__
link to the Function.prototype
which in turn is an instance of Object
and has a __proto__
link to Object.prototype
. The proto link ends here with __proto__
in the Object.prototype
pointing to null
.
Any object can have access to all the properties in its proto chain as linked by __proto__
, thus forming the basis for prototypal inheritance.
__proto__
is not a standard way of accessing the prototype chain, the standard but similar approach is to use Object.getPrototypeOf(obj)
.
Below code for instanceof
operator gives a better understanding:
object instanceof
Class operator returns true
when an object is an instance of a Class, more specifically if Class.prototype
is found in the proto chain of that object then the object is an instance of that Class.
function instanceOf(Func){
var obj = this;
while(obj !== null){
if(Object.getPrototypeOf(obj) === Func.prototype)
return true;
obj = Object.getPrototypeOf(obj);
}
return false;
}
The above method can be called as: instanceOf.call(object, Class)
which return true if object is instance of Class.