Inheritance in Javascript Using Prototype
Last Updated: September 20, 2017
I am going to define super class Vehicle
with make
and model
properties and drive()
method
function Vehicle(){ this.make="" this.model="" this.drive=function(){ console.log(this.make +" " + this.model +" is moving") } }
Then I will define Car
constructor function which will inherit from the Vehicle constructor function
function Car(){ this.year="" } Car.prototype=new Vehicle()
In line 5 , you have Car.prototype=new Vehicle()
statement which is used to inherit method and properties from the Vehicle
super class
Now I will create object named myCar
var myCar= new Car() myCar.make="Honda" myCar.model="Civic Hybrid" myCar.year="2017" myCar.drive()
make,modle properties comes from the super class and year property comes from the subclass. myCar.drive()
will call the drive()
from the super class
If you need you can override the drive()
function in Car
subclass