I borrow from Objective-C. Duh.
No, don’t go away! I promise this post will be worth your time. I’ll be short.
Okay.
With that out of the way, I’ll just say this: I can’t wrap my head around prototype-based inheritance. That is: I can and I do understand it and I would be able to mentally resolve prototype chains easily, but the code is ugly.
Consider the canonical example:
Employee.prototype = new Person();
OMGWTFWHAT?
Why are all Employees referring to a single Person object, whose state is singular? (I know you can redefine state in the Employee objects and the prototype chain for that will work out in the Person methods, but come on!)
Also, how do you get to run the new Person() code in new Employee()? (Answer: you don’t. You have to outsource your constructor call to an initialize method for things to have sense.)
Oh, geeze.
So, what to do? An answer, my friend, is more gun factory methods. By skirting prototype inheritance entirely and using what in the Objective-C world we’d call “swizzling” and in Ruby is called “monkey patching”, not only we can mimic successfully canonical class-based inheritance, but we can even implement trickier stuff like traits. YAY!
Example. Let’s say you’re building a dice-rolling application for yet another certain mobile platform that takes HTML and CSS and JavaScript. RPGistas roll packs of dice of the same kind, where “kind” means “number of faces”: for example, 3d6 means that you roll three six-sided dice (the kind of dice you use in Monopoly — yes, it’s not the only one and the thing can become downright weird. But I disgress).
We want to model that using a class-ish kinda thing in JavaScript. Well, I make a factory method like this:
function Dice(numberOfDice, numberOfFacesPerDie) {
return {
roll: function() {
var i, a = [];
for (i = 0; i < numberOfDice; i++)
a.push(Math.floor(Math.random()
* numberOfFacesPerDie + 1));
// mathematically fair!
return a;
},
numberOfDice: function() { return numberOfDice; },
numberOfFacesPerDie: function() { return numberOfFacesPerDie; }
};
}
Ka-zing! Now a (Pythonesque) var threedeesix = Dice(3,6); gives us an object that rolls three six-sided dice when we do var result = threedeesix.roll();. Hurrah! Also note how we exploit the closure to avoid lots of this.‘s for private state, also killing the this.numberOfDice = numberOfDice boilerplate code (we still need to define functions to expose this state to the outside world, though).
Two steps further: inheritance and super calls. How do we make an object just like a Dice, but that works differently? Some kind of, say, rigged pack o’ dice? Easy: we make a Dice-built object, then we monkey-patch it to suit us.
function RiggedDice(numberOfDice, numberOfFacesPerDie) {
var self = Dice(numberOfDice, numberOfFacesPerDie);
self.roll = function() {
var i, a = [];
for (i = 0; i < self.numberOfDice(); i++)
a.push(self.numberOfFacesPerDie()); // all sixes!
};
var super_numberOfDice = self.numberOfDice;
self.numberOfDice = function() {
// not too many dice or we'll get caught
// by the casino guards.
var x = super_numberOfDice.apply(this);
return (x < 3)? x : 3;
};
return self;
}
Double twistin’ ka-zing! Okay, the super part is not as clean as it could be but, hey, it’s there and it works! Note how this method is organized more or less like an Objective-C init method (down to the return self; at the end). Also note how this takes care of my constructor conundrum above. Also note how this circumvents the other limitation of new — that it must return one object and only one object, which is the one the system just gave us. Enter lots of Flyweight and (in Java) AbstractFactoryFactoryFactories and— well, you don’t have a need to do that anymore, because the “constructor” factory method can return whatever we frickin’ want (again, more or less like an Objective-C init method). We could’ve cached our rigged dice packs by numberOfFacesPerDie, and returned the cached ones rather than making new ones over and over again, for example.
Save the environment!
Ah! Traits! Traits! They’re trivial: just factor out the monkey patching code into a function all its own. For example:
function Comparable(object) {
// assumes object.lessThan() is implemented:
object.equalTo = function(x) {
return !this.lessThan(x) && !x.lessThan(this);
};
object.greaterOrEqualTo = function(x) {
return !this.lessThan(x);
};
object.greaterThan = function(x) {
return object.greaterOrEqualTo(x) && !object.equalTo(x);
};
// ... and so on.
}
Ah, the fresh smell of code reuse in the morning. Just define your object, maybe implement that method or two that the trait requires, and a call like Comparable(object); will add the trait. Simple, conceptually clean, not needing any brain twist to understand. Just like coffee. Clean coffee. Not the greatest of metaphors, but you get the point. Not the coffee.
The obvious objection is, “why not skip all o’ this and use the Class or equivalent facility your framework of choice provides”? That I’d recommend, too, in most cases — but say you’re making generic code that must run on a variety of platforms, some of which bundle other frameworks that redefine the same symbols of your favorite one? (And yes, it has happened in real life.) This is 100% vanilla JavaScript. No framework required. And as simple and as powerful as it gets. Which I like.
And that’s all.

“The fresh smell of code reuse in the morning” was just plain funny. Great post, both for the style and the substance.
Great app, too: “Mover” is why I’m reading this entry.
Ciao!