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 ๐Ÿ™‚

{ 2 comments… read them below or add one }

Tony MacDonell September 13, 2005 at 12:00 am

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.

Reply

aral September 14, 2005 at 12:00 am

Hey Kai, it’s these little things that make life interesting for us in the Flash world! ๐Ÿ™‚

Reply

Cancel reply

Leave a Comment

Previous post:

Next post: