actionscript 3 - weird behavior of variables in anonymous functions? -


could explain why trace result of code below "5,5,5,5,5" rather "1,2,3,4,5" , how make anonymous function refer collect element in array?( in example, "var item" should referring list[0],[1],[2],[3],[4]).

var list:array=[1,2,3,4,5]; var funcs:array=[];  each(var item:int in list){     funcs.push( function(){        trace(item);     }); }  each(var func:function in funcs){     func(); }  trace result: 5,5,5,5,5 

this result of 2 things:

  1. function-level scope in as3: variable declaration inside for each(var item:int in list) equivalent declaring var item:int @ beginning of function (in example, @ start of code).

  2. anonymous functions closures, contain not code specify trace(item), environment code run in. specifically, each of anonymous functions created code knows should use item variable (declared @ function scope) printing (via trace()).

so, happens item gets assigned elements of list, , retains last value (which 5). exists (does not go out of scope), , when anonymous functions fire, each of them looks @ same item , prints same value.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -