notes on javascript, linux, and more

5.06.2009

Multiple Class Inheritance with Prototypes in Javascript

Here is a simple example to demonstrate multiple class inheritance in Javascript. Let's say we are trying to describe a dog named Lily who is is a pit bull & black labrador mix. We can do this by combining a Dog class, a PitBull class, and a BlackLabrador class into a PitLabMix class. Prototyping splits the constructor from the class template, which allows us to inherit from several classes without having to instantiate any of them. In the end, we have an instance of the PitLabMix class named 'lily', which has all the properties of Dog, PitBull, and BlackLabrador. The script makes use of the window.console.log function in Firebug to demonstrate what the final object looks like. For non-Firefox browsers, there is also Firebug Lite.

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

Dog.prototype = {
kingdom : "Animalia",
subkingdom : "Eumetazoa",
phylum : "Chordata",
subphylum : "Vertebrata",
class : "Mammalia",
subclass : "Theria",
order : "Carnivora",
suborder : "Caniformia",
family : "Canidae",
subfamily : "Caninae",
tribe : "Canini",
genus : "Canis",
species : "C. lupus",
subspecies : "C. l. familiaris"
}

function PitBull (name) {
this.name = name;
for (var x in Dog.prototype)
this[x] = Dog.prototype[x];
}

PitBull.prototype = {
build : "Muscular",
demeanor : "Loyal"
}

function BlackLabrador (name) {
this.name = name;
for (var x in Dog.prototype)
this[x] = Dog.prototype[x];
}

BlackLabrador.prototype = {
"fur color" : "Black"
}

function PitLabMix (name) {
this.name = name;
for (var x in Dog.prototype)
this[x] = Dog.prototype[x];
for (var x in PitBull.prototype)
this[x] = PitBull.prototype[x];
for (var x in BlackLabrador.prototype)
this[x] = BlackLabrador.prototype[x];
}

var lily = new PitLabMix('Lily');
window.console.log(lily);

About Me

My photo
chicago, il, United States
I'm a software engineer by profession.

Labels