Nested inheritance in Javascript

Most examples of javascript inheritance only go one level deep (for example, Student inherits (→) from Person). That’s all well and good, but what if you have a long chain for things you want to inherit from?

Say we have A → B → C → D → E, and each has its own methods and attributes. How can they inherit from each other cleanly?

Here is the initial solution:

So, what’s special about the above. Not much… except the the only gotcha is the ordering of:

//you need to make sure you don't override your functions
X.prototype = new Y(); = function(){ .... };

//Bad (trashes foo!) = function(){ .... };
X.prototype = new Y();

Adding methods and properties

Once we have a chain, we naturally want to make objects created from that chain do something useful. The above A, B, C, etc. is a little academic, so lets now use a more “real world” example.

Lets say we have the following inheritance chain of vehicle types:

Vehicle → LandVehicle → Car → SportsCar → RacingCar

We assume that all Vehicles have a “registration” property that is unique for each vehicle we create:

The problem when we run the above is that the registration is not unique! When we are constructing the new RacingCar(), we are using the same prototype for all instances (in fact for any kind of Vehicle).

To solve this problem, we need to make sure that for “this” instance we are given a unique “registration”. To do that, we need to “call()” the function from which we are inheriting from using “this“, like so:

function RacingCar(){}

So, that makes sure that “this” (whatever that is associated with) gets the right “registration” number (i.e., a random number):

Ok, so far so good… but if we start adding methods and unique properties on each level, we are going to have the same problem. So what we can do is just cascade “this” through the inheritance chain:

function LandVehicle(){}
function Car(){}
function SportsCar(){}
function RacingCar(){}

Now we can start individualising each object to our needs. The following shows a complete set of custom objects that inherit from each other. It also shows “static” functions and property being declared (e.g., the make of a Car and getting a randomMake() for either a bike or car):

So there you have it. Classical inheritance JavaScript styles.