This figure again shows that every object has a prototype. Constructor function Foo also has its own
__proto__
which is Function.prototype, a
The __proto__
property of an object is a property that maps to the prototype
of the constructor function of the object. In other words:
instance.__proto__ === constructor.prototype // true
This is used to form the prototype
chain of an object. The prototype
chain is a lookup mechanism for properties on an object. If an object's property is accessed, JavaScript will first look on the object itself. If the property isn't found there, it will climb all the way up to protochain
until it is found (or not)
function Person (name, city) {
this.name = name;
}
Person.prototype.age = 25;
const willem = new Person('Willem');
console.log(willem.__proto__ === Person.prototype); // the __proto__ property on the instance refers to the prototype of the constructor
console.log(willem.age); // 25 doesn't find it at willem object but is present at prototype
console.log(willem.__proto__.age); // now we are directly accessing the prototype of the Person function
Our first log results to true
, this is because as mentioned the __proto__
property of the instance created by the constructor refers to the prototype
property of the constructor. Remember, in JavaScript, functions are also Objects. Objects can have properties, and a default property of any function is one property named prototype.
Then, when this function is utilized as a constructor function, the object instantiated from it will receive a property called __proto__
. And this __proto__
property refers to the prototype
property of the constructor function (which by default every function has).
JavaScript has a mechanism when looking up properties on Objects
which is called 'prototypal inheritance', here is what it basically does:
__proto__
property. There, it checks if the property is available on the object referred to by __proto__
.__proto__
object, it will climb up the __proto__
chain, all the way up to Object
object.prototype
chain, it will return undefined
.For example:
function Person (name) {
this.name = name;
}
let mySelf = new Person('Willem');
console.log(mySelf.__proto__ === Person.prototype);
console.log(mySelf.__proto__.__proto__ === Object.prototype);