notes on javascript, linux, and more


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) { = 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) { = name;
for (var x in Dog.prototype)
this[x] = Dog.prototype[x];

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

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

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

function PitLabMix (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');

About Me

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