portfolio | contact
July
Monday the 27th

super easy inheritance in javascript

Monday, 5:20 PM
One of the things that have always rubbed me the wrong way with regard to javascript libraries is that they often try to shoe horn javascript into a class based model. Javascript was intentionally designed to be a prototype based language. Rather than simply bitching about it, I decided to look into developing a concept of inheritance that was in step with javascript's conceptual roots.

First, a bit of background. The type of OOP you're most likely familiar with is class based. Remember Plato's theory of forms? There is an infinitive, unconjugated, universal concept of horse, and then there is this horse and that horse. This is how class based OOP, works more or less. You have a Horse class, and then instances of Horse. Prototype based OOP is different. It's much more bendy and flexible. Inheritance is achieved by cloning instances of existing objects. So for example, mammal is just an object with a few methods and properties. Human is a clone of mammal but with a postRandomCrapToFacebook() method.

mammal = {
sound: "",
eyes:2,
blood:"warm",
talk: function(){alert(this.sound)},
eat: function(){alert("munch munch")},
sleep: function(){alert("zzzzzzzzz")}
}

pig = ((new function(){}).prototype = mammal);
pig.sound = "oink";
pig.talk();
pig.eat();
pig.sleep();

porky = ((new function(){}).prototype = pig);
porky.sound = "thats all folks";
porky.dance = function(){alert("ta da!")}
porky.talk();
porky.dance();

dog = ((new function(){}).prototype = mammal);
dog.investigate = function(){alert("sniff sniff sniff")};
dog.sound = "BARK BARK!";
dog.investigate();
dog.talk();

yorkie = ((new function(){}).prototype = dog);
yorkie.sound = "barkbarkbarkbarkbark";
yorkie.investigate();
yorkie.talk();
yorkie.sleep();

granted, this is a bit wonky: yorkie = ((new function(){}).prototype = dog);

you'd probably want to create a function that would handle your cloning. Maybe something like this:

function copyOf(sire){
progeny = function(){};
progeny.prototype = sire;
return progeny
}

yorkie = copyOf(dog);

This is neat because you can have complex family trees, stitching functionality from this prototype into the next while each remains a functional object. There are no immovable static forms that merely serve as unalterable templates. I'm aware that many developers are "HORRIFIED and DISGUSTED" by this concept, but its really kind of liberating once you've acclimated to it.

◄ back