After a while writing something. This is a fresh article for new coders. Please follow daily content coming. So let's start. Inheritance is the way to make one class extend the functionalities of another class, that is adding more functionalities to an already existing class.
extends
keyword is used to inherit a class.
class Animal {
eat() {
console.log('Eating');
}
}
class Human extends Animal {
speak() {
console.log('Running');
}
}
Now when we create any object for the Human class, the object can acess the methods of both Human and Animal classes.
const human = new Human();
human.run();
human.eat();
How it works
When using classes, the members you declare in them are stored in special [[Pototype]] key in the objects.
All the objects of Animal class will share the same [[Pototype]], which is the Animal class itself.
When accessing the method or field, JavaScript looks for it in the [[Pototype]].
const Animal = new Animal();
animal.eat();
// .eat() is available in the prototype.
On extending a class, the prototype of the Human class is of type Animal.
When we evoke the eat() method, it is first searched in the Human prototype. Since it is not there, it continues to search in Animal prototype (which contains eat method).
Overriding
It is possible to override some methods in base class to provide new functionality.
class Animal {
eat() {
console.log('Animal eats');
}
}
class Human extends Animal {
eat() {
console.log('Human eats');
}
}
const human = new Human();
human.eat();
// --> 'Human eats'
Inside the child class, the super keyword refers to the parent object. This can be used to invoke any method in the parent class.
class Human extends Animal {
eat() {
super.eat();
console.log('Human eats');
}
}
const human = new Human();
human.eat();
// --> 'Animal eats'
// --> 'Human eats'
Thanks for Reading.
Comments (0)