Open In App

Explain Prototype Inheritance in JavaScript

In this article, we will try to understand the facts that are required to effectively understand what exactly Prototype Inheritance in JavaScript means or what does it actually implies with the help of several examples of approaches.

Let’s understand the basics behind Prototype Inheritance in JavaScript.



Prototype Inheritance in JavaScript: Following bullet points will try to analyze the basics behind Prototype Inheritance in JavaScript-

Following pictorial representation, containing some sample values will help us to understand Prototype Inheritance in a much better and effective way-



Now that you have understood a brief detailed description of Prototype inheritance let us see and understand Prototype Inheritance with several following approaches-

Approach 1: using __proto__

In this approach, we will use __proto__, which is the special name for the internal and hidden prototype called [[Prototype]]. We will store all the properties of the rabbit in the animal prototype object and thereafter we may access it whenever it is required. This __proto__ is a bit old as well as an outdated approach that exists for some historical reasons associated with JavaScript.

Example: In this approach, we are using the above-explained approach.




let animal = {
    animalEats: true,
};
 
let rabbit = {
    rabbitJumps: true,
};
 
// Sets rabbit.[[Prototype]] = animal
rabbit.__proto__ = animal;
console.log(rabbit.animalEats);
console.log(rabbit.rabbitJumps);

Output
true
true

Approach 2: Using Object.setPrototypeOf() method

In this approach, we will use the new JavaScript methods to implement JavaScript Prototype Inheritance, Here we will use Object.setPrototypeOf() method takes two parameters first one is the object which is to have its prototype set and the second one is the object’s new prototype. Thereafter we have declared two objects and using those two objects, we will set one of the objects as the prototype object for another object.

Example: In this example, we are using the above-explained approach.




let rabbit = {
    rabbitJumps: true,
};
let animal = {
    animalEats: true,
};
Object.setPrototypeOf(rabbit, animal);
console.log(rabbit.animalEats);
console.log(rabbit.rabbitJumps);

Output
true
true


Article Tags :