开发者

Anonymous functions accessing local variables [ActionScript - Flex 3.5]

I am having a situation with my actionscript/flex front end.

 for each (var sym:String in ["A开发者_如何学C","B","C"]) {

                const handler = function (data:Object):void { Alert.show(sym); }                

                asyncCallback(handler);

   }

I am expecting to have 3 Alert windows containing A, B and C. But the actual result is 3 alert windows all showing C !


This one is a bit tricky. You have to wrap your handler creation inside another function.

try:

for each(var sym:String in ["A","B","C"]) {
    function createHandler(val:String):Function {
        var handler = function(data:Object):void { 
            trace(val); 
        }
        return handler;
    }
    var handler:Function = createHandler(sym);
    asyncCallback(handler);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜