Friday, April 16, 2004

Wacky instance variable initialization

Came across something that is so wacky its hard to believe its true.

We had a component where we initalize an instance variable to an empty object in the class declaration as in:

var myVar = {};

Nothing too earth shattering here!

So its clear we should have an instance variable intialized to an empty object, so I could then do something like this;

myComp.myVar.empty=true;
or this
myComp.myVar.name=_name;

and then trace(myComp.myVar.name) will display the components instance name.

OK so whats the issue .. well it seems that the object that myVar points to is static (or global if you will) so now every instance will see myVar.name as the same name and NOT its own instance name.

We thought we must be missing something about using "{}" so we tried using new Object() instead but to no avail, the object created is always static and all instances will be pointing at the same object.

We resolved it in the end by leaving the var as undefined and then in the ancestor "init" method setting it to an empty object, then it all works correctly or I should say works as expected.

Ok there maybe be some obscure explanation for why this behavior is correct but at least its not obvious nor is it in line with what you would expect in other languages and could catch you out in building you own components so beware...

unless of course its a neat trick you would like to exploit...

No comments:

Post a Comment