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:
function-level scope in as3: variable declaration inside
for each(var item:int in list)
equivalent declaringvar item:int
@ beginning of function (in example, @ start of code).anonymous functions closures, contain not code specify
trace(item)
, environment code run in. specifically, each of anonymous functions created code knows should useitem
variable (declared @ function scope) printing (viatrace()
).
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
Post a Comment