Inheritance in Javascript Using Extend Function

September 20, 2017

You can create function called extend to make subclassing process

/* extend function */

function extend(child,parent){
   var Temp=function(){}
   Temp.prototype=parent.prototype
   child.prototype= new Temp()
   child.prototype.constructor=child
}

This function will do what other languages do using extend keyword

Now you can create the parent class Vehicle and create the subclass Car from it

function Vehicle(){
    this.make=""
    this.model=""

}

Vehicle.prototype.drive=function(){
    console.log(this.make +" " + this.model +" is moving")
}


function Car(){
    this.year=""
}

extend(Car,Vehicle)

var myCar= new Car()
myCar.make="Honda"
myCar.model="Civic Hybrid"
myCar.drive()

In line 16, I am using extend() method for subclassing process