Home >>Javascript Tutorial >JavaScript Inheritance
The JavaScript inheritance is basically a mechanism that allows the users to create new classes on the basis of the already existing classes. JavaScript Inheritance delivers flexibility to the child class in order to reuse the methods and variables of a parent class.
In order to create a child class on the basis of a parent class JavaScript extends keyword is used. JavaScript extends keyword facilitates its child class to obtain all the properties and behavior of its parent class.
Please note that the following mentioned points are recommended to keep in mind:
Here is this example date object is extended to display the today's date:
<script> class DateTime extends Date { constructor() { super(); } } var m=new DateTime(); document.writeln("Current date:") document.writeln(m.getDate()+"-"+(m.getMonth()+1)+"-"+m.getFullYear()); </script>
Here is another example displaying the year value from the given date:
<script> class DateTime extends Date { constructor(year) { super(year); } } var m=new DateTime("November 15,2019 20:22:10"); document.writeln("Year value:") document.writeln(m.getFullYear()); </script>
Here, in this example sub-class that extends the properties of its parent class is declared:
<script> class Bike { constructor() { this.company="suzuki"; } } class Vehicle extends Bike { constructor(name,price) { super(); this.name=name; this.price=price; } } var v = new Vehicle("Hayabusa","1400000"); document.writeln(v.company+" "+v.name+" "+v.price); </script>
In the following example, prototype based inheritance is performed. There is no need to use class and extends keywords in this approach.
<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("Suzuki"); Vehicle.prototype=bike; //Now Bike treats as a parent of Vehicle. var vehicle=new Vehicle("Hayabusa",1400000); document.writeln(vehicle.getCompany()+" "+vehicle.name+" "+vehicle.price); </script>