Tuesday, December 2nd, 2008

Implementing super in JavaScript

Category: 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:

javascript

  1. function createSuper(self, opt_constr) {
  2.   var constr = opt_constr || arguments.callee.caller;
  3.   function supr() {
  4.     return constr.superClass.apply(self, arguments);
  5.   };
  6.   supr.__noSuchMethod__ = function(name, args) {
  7.     if (typeof constr.superClass.prototype[name] == 'function') {
  8.       return constr.superClass.prototype[name].apply(self, args);
  9.     }
  10.     throw Error('No such method, ' + name);
  11.   };
  12.   return supr;
  13. }

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, …);

Posted by Dion Almaer at 6:43 am
1 Comment

++---
2 rating from 30 votes

1 Comment »

Comments feed TrackBack URI

I guess that this is the kind of “hacks” for missing features in the language that scares developers away from JavaScript.

Comment by Jeria — December 5, 2008

Leave a comment

You must be logged in to post a comment.