Tuesday, June 12, 2007

Array instantiation for actionscript classes

If you want to avoid some nightmares, don't instantiate the arrays in the variable definition inside a class.
i.e. DON'T do the following

class myClass {

var my_array:Array = new Array()

function myClass()
{
}

....
}


Coz this would end up with a behaviour similar to having the my_array defined as static. What I think that it is happening, is that it won't re-initialise the variables when you instantiate a class but will just give you a reference to the array. Thus each instance you create will have a reference to the same array. How dumb!

So the solution is ofcourse to move the array instantiation in the constructor, like so:

class myClass {

var my_array:Array;

function myClass()
{
my_array = new Array();
}

....
}

2 comments:

Unknown said...

This is where you see how Actionscript (at least up to v2.0) is still relatively young. In a language like Java the ambiguity is eliminated by everything being a member of the instance unless 'static' is defined. In C++ the compiler is supposed to stop you from initializing variables in a class definition unless they are const (and I *think* static too - don't quote me on this).

Daniel Upton said...

Thank you! I've been beating my head against the wall for 30 minutes!