Pseudo static variables in Flash/Flex

by kai on 13/09/2005

The other day I was running into an odd issue. I've developed a Flex component and inherited two other components from this parent component. In the parent component I've defined a private variable inside of an mx:Script block:

private var myDataArray = new Array();

Additionally the parent component offered a private function to push objects into that array.

I created instances of the two sub-classed components and called the private function of the parent component to fill the instance variables (well, I thought they were instance variables :-).

What happened was that both instances of my sub-classed components shared the same variable, because all the data I put into one was visible for the other one as well and vice versa. The variable behaved like a static variable in Java. It was not too difficult to find the error (the initialisation of the array didn't take place in the constructor as it should have, aaaargs), but I wondered why the hell Flex did create this pseudo-static class variable until Aral told me that this is some sort of AS 1 Flash Player relict. Good to know, but a weird behaviour :-)

← PreviousNext →I'm a Macromedia Master Instructor

2 comments

Tony MacDonell 13/09/2005

This is why: AS2: private var myDataArray = new Array(); AS1: MyClass.prototype.myDataArray = new Array(); So when you create a few instances of my class, they all refer to the same object on the Class's prototype.

aral 14/09/2005

Hey Kai, it's these little things that make life interesting for us in the Flash world! :)