Search code examples
arraysactionscript-3inheritanceextend

Extend the Array class in AS3


I've been learning OOP recently and have decided to take that paradigm shift into it (its not easy...at ALL) and in trying some of the concepts of it I'm having a bit of a problem inheriting from the Array class in ActionScript 3.0 (not that i have tried in AS 2.0)...sigh. Anyway I am trying to call the parent constructor to instantiate the ...rest arguments from within the child class like so

public class CustomArray extends Array{

    public function CustomArray(...rest):void {
        super(rest);
    }
}

And I keep getting this Error from the output...

ReferenceError: Error #1056: Cannot create property 0 on classes.CustomArray.

...to my utter dismay :(.

I'm obviously doing something wrong but for the love of me can't seem to find out what it is. Really in need of help. Thanks.


Solution

  • Unfortunately in AS3 you can't call super constructor and pass parameters to it in Function::apply style, so in your Array implementation array with length=1 and one element (the passed rest parameter with the type of Array) will always be created. If you want to implement the default AS3 Array constructor behavior:

    Array Constructor
    public function Array(... values)
    
    Parameters
        ... values — A comma-separated list of one or more arbitrary values.
    
    Note: If only a single numeric parameter is passed to the Array constructor, 
    it is assumed to specify the array's length property.
    

    You have to add some code to the constructor of your CustomArray:

    public dynamic class CustomArray extends Array
    {
        public function CustomArray(...rest)
        {
            super();
    
            var i:int, len:int;
            if(rest.length == 1)
            {
                len = rest[0];
                for (i = 0; i < len; i++) 
                    this[i] = "";
            }
            else
            {
                len = rest.length;
                for (i = 0; i < len; i++) 
                    this[i] = rest[i];
            }
        }
    }
    

    Also don't forget to make this class dynamic.