What is prototype and prototype chain in JavaScript
Each JavaScript object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until a object is reached with null as its prototype. null has no prototype and acts as the final link in this prototype chain.
Multiple inheritance with prototypes is referred to as a prototype chain.
function Car() {
this.make = "Honda";
this.model = "Civic";
}
let c = new Car();
Car.prototype.fuel = "Gas";
console.log(c.make);
// Is there an 'make' own property on c? Yes, and its value is "Honda"
console.log(c.model);
// Is there a 'model' own property on c? Yes, and its value is "Civic"
console.log(c.fuel);
// Is there a 'fuel' own property on c? No, check its prototype. Is there a 'fuel' property on c.[[Prototype]]? Yes, and its value is "Gas"
// The notation someObject.[[Prototype]] is used to represent the prototype of someObject
To check whether an object has a property defined on itself
and not somewhere on its prototype chain, it is necessary to use the
hasOwnProperty
method which all objects inherit from Object.prototype
.
c.hasOwnProperty("make"); //true
c.hasOwnProperty("fuel"); //false
All functions have a special property named prototype
.
function foo() {
return 'foo';
}
// Function foo inherits from Function.prototype
References:
Categories :
JavaScript