Javascript-Inheritance
The JavaScript inheritance is a mechanism that will be used to create new classes on the basis of already existing classes. The inheritance is flexible to the child class to reuse the methods and variables of a parent class.
The JavaScript extends keyword is to create a child class on the basis of a parent class. It facilitates the child class to acquire all the properties and behavior of its parent class.
- It maintains an IS-A relationship.
- The extends keyword is used in class expressions or declarations.
- Using the extends keyword, we can acquire all the properties and behavior of the inbuilt object as well as custom classes.
- We can also use a prototype-based approach to achieve inheritance.
JavaScript extends Example: inbuilt object
Display today’s date:
<!DOCTYPE html>
<html>
<body>
<script>
class Moment extends Date {
constructor() {
super();
}}
var m=new Moment();
document.writeln("Current date:")
document.writeln(m.getDate()+"-"+(m.getMonth()+1)+"-"+m.getFullYear());
</script>
</body>
</html>
OUTPUT:
Current date: 8-1-2021
Example: Custom class
The sub-class extends the properties of its parent class.
<!DOCTYPE html>
<html>
<body>
<script>
class Bike
{
constructor()
{
this.company="Honda";
}
}
class Vehicle extends Bike {
constructor(name,price) {
super();
this.name=name;
this.price=price;
}
}
var v = new Vehicle("Shine","90000");
document.writeln(v.company+" "+v.name+" "+v.price);
</script>
</body>
</html>
OUPTUT:
Honda Shine 90000
Example: a Prototype-based approach
In JavaScript, inheritance is supported and also using the prototype object(no need to use class and extends keywords).
<!DOCTYPE html>
<html>
<body>
<script>
//Constructor function
function Bike(company)
{
this.company=company;
}
Bike.prototype.getCompany=function()
{
return this.company;
}
//Another constructor function
function Vehicle(name,price) {
this.name=name;
this.price=price;
}
var bike = new Bike("Honda");
Vehicle.prototype=bike; //Now Bike treats as a parent of Vehicle.
var vehicle=new Vehicle("Shine",80000);
document.writeln(vehicle.getCompany()+" "+vehicle.name+" "+vehicle.price);
</script>
</body>
</html>
OUTPUT:
Honda Shine 80000