Saturday, December 6, 2008

Implementing super in JavaScript

Erik Arvidsson seems to be having fun going through exersizes getting JavaScript to do something his way. The latest little foray is Using catch-alls to implement super.

Firstly, catch-alls are the ability to use the SpiderMonkey only __noSuchMethod__ meta programming trick. The good news is that this seems to be coming to ECMAScript Harmony (I hope we here how the ECMA working group meeting went in Kona soon!).

Erik used this trick to build a createSuper method:

function createSuper(self, opt_constr) {
var constr = opt_constr || arguments.callee.caller;
function supr() {
return constr.superClass.apply(self, arguments); }
supr.__noSuchMethod__ = function(name, args) {
if (typeof constr.superClass.prototype[name] == 'function') {
return constr.superClass.prototype[name].apply(self, args); }
throw Error('No such method, ' + name);
}
return supr;
}

which you can then use via var supr = createSuper(this);
Of course, as Erik points out, you can just use FooClass.superClass.method.call(this, …);

http://ajaxian.com/archives/super-js

No comments: