Friday, October 17, 2008

ActionScript scoping weirdness

Today I got the following error when I ran my Flex app:


TypeError: Error #1010: A term is undefined and has no properties.


Some quick searching on the web didn't reveal much except that it might have to do with a DisplayObject having visible == false. Great, except the object in question isn't a DisplayObject.

I looked into the code and saw this:

private function foo() : void
{
myObject.myProp = "Hello World";

var myObj : MyClass = new MyClass();

// stuff
}

The problem is that I was accidentally using myObject before actually creating it. In any other language, this would generate a compile error, but ActionScript, in its infinite wisdom, scopes the variable to the entire function, not just to the code following the declaration.

The solution: Move the offending line to after the declaration.

No comments: