Prototype and Prototype Chaining
Table of contents
No headings in the article.
What is a prototype?
Can we assign properties and functions to the prototype? if yes, how can we do it?
What is prototype chaining?
In object-oriented programming, every class created is derived from a super class or parent class. In a prototype-based programming language, every class or object is derived from a prototype object.
What is a prototype?
Prototype is the object from which all objects are derived. Prototype gives addition properties and methods to our object. Getting addition properties from another object is called inheritance. Let us understand it better from an example.
let fun = {
isfun : true,
adventure : funtion(){
console.log(`Is adventure is fun for all true or false: ${isfun}`);
}
};
console.log(fun);
Can we assign properties and functions to the prototype? if yes, how can we do it?
The answer is yes, we can create variables and functions at prototype level. By doing this we have an advantage, if we what some variables and function throughout the project or any program we can assign to a prototype object and access then. We will understand with above example.
let fun = { // created object called fun
isFun : true,
adventure(){
console.log(`Is adventure is fun for all true or false: ${isFun}`);
}
};
console.log(fun);
Object.prototype.camp="Mt Everest"; // assiging variable to prototype
let activities = funtion(){
console.log("Treking is fun",this.isfun);
}
object.prototype.activities=activities //assigning funtion to prototype
}
console.log(fun);
What is prototype chaining?
Before learning we need to know a concept called inheritance.
Inheritance: Inheritance is a mechanism in which one object inherits all the attributes and behaviors of a data members and member functions available in the parent class.
When we are trying to access an variable. First it is searched in our object if the variable is present then we get our output. If the variable is not present in our object the it is searched in parent object until the last object it have inherited.
let fun = { // created object called fun
isFun : true,
adventure(){
console.log(`Is adventure is fun for all true or false: ${isFun}`);
}
};
let learning = {
islearn : true,
study : funtion(){
console.log(`Learning javascript is fun`);
}
}
learning.__proto__ = fun;
console. log(learning);
console.log(learning.isFun); // true