Javascript Inheritance

I’m always looking for a good solid javascript inheritance approach that fully supports javascript prototypical inheritance.  The one I’m going to show today will use Object.create – so if you are supporting older browsers, you will want to make sure you have the es5-shim in your project (which I highly suggest having anyway!).

Let’s create a scenario, where we have base ‘Vehicle’ and we’ll show how to extend that with a ‘Car’ object.

Vehicle:

function Vehicle(name) {
this.name = name;
}

Vehicle.prototype.getDescription = function(){
return this.name;
}

Vehicle.prototype.getType = function(){
return ” is a vehicle”;
}

Car

function Car(name, model){
Vehicle.call(this, name); //this will inherit all the instance properties
this.model = model; //add additional instance properties
}

Car.prototype = Object.create(Vehicle.prototype);  //very important as we want to inherit the prototype properties as well!

Now let’s say that we want to override the getType call for Car:

Car.prototype.getType = function(){
return “this is a car!”;
}

We can also extend an existing base (aka super call)

Car.prototype.getDescription = function(){
Car.prototype.getDescription.call(this) + ” is my favorite car!”;
}

That covers prototype/javascript inheritance – again, if you are using IE8, etc… you will need the es5-shim as Object.Create isn’t supported!