In AS2, you can pass parameters to a super class's constructor using super() . This is handy, but what if your constructor accepts an undefined number of parameters, and you want to pass them all to your super constructor (think of the Array class, for instance)? Sounds easy - you should just be able to use "super.apply(this,arguments)", right? Wrong...

BEGIN EXTENDED ENTRY

In AS2, you can pass parameters to a super class's constructor using super() like so:

class MySubClass extends MySuperClass {
   function MySubClass(p_param) {
      super(p_param);
    }
}

This is handy, but what if your constructor accepts an undefined number of parameters, and you want to pass them all to your super constructor (think of the Array class, for instance)? Sounds easy - you should just be able to use "super.apply(this,arguments)", right?

Wrong. Two things get in the way:
  1. The compiler does not interpret "super" as being a function, and will return "There is no method with the name 'apply'."
  2. Because the compiler can't find a call to super() in the sub class constructor (it isn't smart enough to understand super.apply()), it inserts an empty super() call at the beginning of the sub class constructor, so even if you get super.apply to work, the constructor will be called twice!


I wrestled with this issue for a bit, then talked it through with Jonas Galvez, who came up with a solution. It's a bit hackish, but it works! Here's what it looks like:

class MegaArray extends Array {
   function MegaArray() {
      super; // tricks the compiler
      __proto__.constructor.apply(this, arguments);
    }
}

Basically, it tricks the compiler into thinking we have called the super class's constructor, then we really call it using apply.

Just don't try spelling constructor as "contructor", or you'll spend 20 minutes wondering why the heck it doesn't work! :P

Nice work Jonas!


EDIT: Sometimes you look too hard and make things more complex than they have to be... It looks as though this will work too (thanks David):

class MegaArray extends Array {
   function MegaArray() {
      super.constructor.apply(this, arguments);
    }
}