Unreachable, existing variable
I'm new at as3, maybe thats the reason why i don't understand, why the setInterval
causes an error.
<mx:Script>
<![CDATA[
import flash.utils.setInterval;
import mx.controls.Alert;
[Bindable]
public var MyInt:int = 500;
setInterval(function():void{ ++MyInt; },1000);
]]>
</mx:Script>
I have a label where the value of MyInt
gets visible, the bind works perfect, i've tested it several ways, and i i create a button it grows the number, but if i use the setInterval
function i get an error: Access of undefined property myInt
.
Why? What does cause this? Please explain it, so I can avoid errors like this. Thanks
I don't know much about Flex, but I think the problem is that this code:
setInterval(function():void{ ++MyInt; },1000);
Is run like if it was placed in a class definition, outside any function. That makes the code a static initializer. That is, it's run in a static context, which means it has no access to any instance, since no instance has yet been created when the code runs.
This seems to prove it:
public static var MyInt:int = 500;
setInterval(function():void { ++MyInt; trace(MyInt); },1000);
With static
, the code works fine.
You probably don't want MyInt
to be static, though. So you should put the setInterval
call within an instance method. Assuming init
is called from the mx:Application
initialize
callback, this should work fine:
[Bindable]
public var MyInt:int = 500;
private function init():void {
setInterval(function():void { ++MyInt; trace(MyInt); },1000);
}
精彩评论