scope - Javascript: Issue with variable scoping and anonymous function -
i have sample code:
function(){ var events = []; var pages = ["a", "b", "c"]; for(var pageindex in pages){ var pagename = pages[pageindex]; var e = function(){ console.info(pagename); }; events.push(e); } for(var eventindex in events){ console.info("index: " + eventindex); events[eventindex](); } }
output:
index: 0 c index: 1 c index: 2 c
desired output:
index: 0 index: 1 b index: 2 c
is there standard practice this?
each e
function create closure accesses external variable pagename
enclosing code. pagename
see value at time function run. @ end of loop pagename
"c"
, of functions use when executed.
you can fix wrapping function in following way, bind current value of pagename
function create:
function(){ var events = []; var pages = ["a", "b", "c"]; for(var pageindex in pages){ var pagename = pages[pageindex]; var e = (function(data) { return function() { console.info(data); }; })(pagename); events.push(e); } for(var eventindex in events){ console.info("index: " + eventindex); events[eventindex](); } }
Comments
Post a Comment