In this article, we will discuss “How to Implement Class Inheritance in JavaScript?”. Since JavaScript is object-oriented programming language and inheritance is a basically useful in object-oriented language, so it is the most probable question. So let’s discuss a bit about it.
Solution:
Class inheritance is a pretty basic concept which enables you to define a class which take all functionality from the parent class. Inheritance is useful, when we need to make a class reusable and to increase reusability and to decrease code length. Let’s understand with example code:
<script>
class Car{
constructor(name, model){
this.name = name;
this.model = model;
}
start(){
console.log(this.name);
}
end(){
console.log("Car stopped!!!");
}
}
class electric extends Car{
dashboard(){
console.log("Child Method");
}
start(){
super.start();
super.end();
this.dashboard();
}
}
evCar = new electric('Tesla', 'A320');
evCar.start();
</script>
Here, we have created a basic class named Car, where we have created a constructor with two arguments, name and model. Then we created two properties using this keyword, then again we added methods named start and end with some console.log().
Now let’s inherit this Car class to electric class, To inherit and use car classes elements in electric class using extends keyword. Also, we have added a method which is method of electric class. Remember that, Child class’s method cannot be accessed in parent class, but elements of parent class can be accessed in child classes.
To get access to the methods from parent class, we will use super keyword. Here we inherited start() and end() methods, which are created in parent class, and now it can be accessed in child class. Lastly, we have created an object of electric class named evCar with two arguments, and we just called start() method. Also, note that, you can make object of parent class which only can access methods of parent class.
Output:
Tesla
Car stopped!!!
Child Method