Prototype and Prototypal Inheritance in JavaScript
Prototype is a core concept in JavaScript which helps us to reuse code in our program.
Table of contents
Prototype is a core concept in JavaScript which helps us to reuse code in our program. In this blog, I will explain what is a prototype, the prototype chain and how prototypal inheritance works.
Prototype
Let's understand this topic by simple code.
In the above code, I have created an empty object obj
and inserted name
and age
properties to it.
Let's see by accessing those properties.
If you observe the above code, We only added two properties to our object obj
but we are able to call toString()
function which we didn't initialise. Similarly when we try to call anything()
, We got an error.
Now, Let's try with an array.
Now, along with array items, We are seeing all the array methods in a special object called prototype
This mechanism of inheriting features from another object is called a prototype.
Prototype chain
We can access the prototype object by calling __proto__
Let's see what we have in the prototype of the object we created earlier.
Let's see what we have in the prototype of the array.
If we observe carefully, We have prototype of the array and prototype of the object as its prototype and both are the same. We can prove it by the below code.
This chaining of the prototypes is known as the Prototype chain. Also, from this, we can say that everything in JavaScript is some sort of Object.
Prototypal Inheritance
Prototypal Inheritance is very different from Inheritance in other languages. Let's understand this concept by an example.
Here, We have created an object human
which has a function talk()
and we have created another object superman
(Object.create()
is just another way of creating objects.)by inheriting human.
Now, We can call talk()
from superman as well because it is inheriting the human object. Let's prove it.
In the above code, I have created another method inside superman. Now We can access both fly()
and talk()
from the superman object.
And, If we observe carefully, the inherited methods are not directly under the superman object. those are added to the prototype of superman object. This type of inheritance is called Prototypal Inheritance.
I hope you learnt something new by reading this post. Please like this and share this post with your friends and community, it motivates me to write more awesome blog posts.
Will see you in my next blog post ๐