Inheritance in JavaScript
inheritance in JavaScript allows objects to inherit properties and methods from other objects. Each object in JavaScript has an internal link to another object called its . This chain of s forms the chain.
When you access a property or method on an object, JavaScript first checks the object itself. If the property or method isn’t found, it moves up the chain until it finds the property or reaches the end of the chain (null).
const parent = {
greet: function () {
console.log("Hello from the parent object!");
}
};
const child = Object.create(parent);
child.sayHi = function () {
console.log("Hi from the child object!");
};
child.greet();
child.sayHi();
Output
Hello from the parent object! Hi from the child object!
Chain
The chain is the mechanism that JavaScript uses to resolve properties and methods. If an object doesn’t have a requested property, the JavaScript engine searches up the chain.
function Animal(name) {
this.name = name;
}
Animal..speak = function () {
console.log(`${this.name} makes a sound.`);
};
const dog = new Animal("Buddy");
console.log(dog.name);
dog.speak();
Output
Buddy Buddy makes a sound.
In the above pictorial representation, we have taken an example to illustrate the Inheritance between a rabbit and another create object which is an animal. We will set the rabbit's object as an animal object wherein we will store all the values of rabbit for a purpose that if in the case in while rabbit properties are missing then JavaScript will automatically take it from animal object.
Now that you have understood a brief detailed description of inheritance let us see and understand Inheritance with following approaches -
- Using __proto__
- Using Object.setOf() method
1. Using __proto__
In this approach, we will use __proto__, which is the special name for the internal and hidden called [[]]. We will store all the properties of the rabbit in the animal 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.
let animal = {
animalEats: true,
};
let rabbit = {
rabbitJumps: true,
};
// Sets rabbit.[[]] = animal
rabbit.__proto__ = animal;
console.log(rabbit.animalEats);
console.log(rabbit.rabbitJumps);
Output
true true
2. Using Object.setOf() Method
In this approach, we will use the new JavaScript methods to implement JavaScript Inheritance, Here we will use Object.setOf() method takes two parameters first one is the object which is to have its set and the second one is the object's new . Thereafter we have declared two objects and using those two objects, we will set one of the objects as the object for another object.
let rabbit = {
rabbitJumps: true,
};
let animal = {
animalEats: true,
};
Object.setOf(rabbit, animal);
console.log(rabbit.animalEats);
console.log(rabbit.rabbitJumps);
Output
true true