Prototypal Inheritance in Javascript - Easy and Practical Way
You are here which means this concept might seem very confusing to you. Let's deep dive and understand.
Table of contents
Before you understand what prototypal inheritance is, I let you know that don't confuse this with a classical inheritance that you might have learned from other languages.
You might have come across this Everything is javascript is an object, if not then you will get to know here.
Before we jump on to what prototypal inheritance is, we need to understand what a prototype is. So according to MDN - Prototypes are the mechanism by which JavaScript objects inherit features from one another.
Let's understand with an example.
//Let's create a user object
let user = {
getUserInfo: function () {
console.log(`${this.name} is from ${this.city}`);
},
getOccupation: function () {
console.log(`${this.name} is a ${this.role}`);
},
};
// developer object which inherits user object
let developer = Object.create(user);
developer.name = "Bidisha";
developer.city = "Kolkata";
developer.role = "Engineer";
developer.getUserInfo();
developer.getOccupation();
Let's run this code and see our browser console.
So the code runs and it logs the user info and occupation. But as you can see the developer object only contains properties that are city, name, and role then how is it able to access function getUserInfo and getOccupation. As developer object inherits user object the properties of user object gets attached inside proto of developer object . Whenever developer object is unable to find the properties in its own boundary it checks inside its proto and if it is unable to find then it checks developer.__proto__.__proto__
and traverse down the chain until it points to null
.
So eventually it forms a chain like this.
From the above image, we can see that proto
of developer object points to user object, then proto
of user object or developer.__proto__.__proto__
points to Object.prototype which eventually points to null
.
Have you ever wondered that whenever you create an array and put a dot after the label of your array your IDE gives you a list of functions that can be applied? Where are they coming from?
All these functions of array is getting inherited from Array.prototype
.
And further Array.prototype.__proto__
is also Object.prototype.
.
So in the prototype chain Object. prototype is the point from where prototype chaining starts and objects like Arrays
, String
, Function
, Numbers
and Boolean
gets inherited from.
Summary
So in javascript objects are inherited via prototype chaining. Each and every object in javascript has the proto property where the objects they are inheriting from are attached.
I hope you have learned and understand how prototypal inheritance works inside javascript. If this content benefits you please show some love by liking and sharing and also feel free to comment and correct if you think I have missed something.