2 min read
Let's understand this topic by simple code.
In the above code, I have created an empty object
obj and inserted
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
This mechanism of inheriting features from another object is called a prototype.
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.
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
Object.create() is just another way of creating objects.)by inheriting
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
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 😊