Javascript scope and calling a function -


my code:

for (var = 0; < mapinfos.length; i++) {              var x = function () { dostuff(i); };             google.maps.event.addlisteneronce(mapinfos[i].map, 'tilesloaded', x); } 

the dostuff method alerts value of i. mapinfos has 2 entries, you'd expect alert 0 , 1, instead alerts 2 , 2. can appreciate vaguely why doing (although var should keep local scope of loop?) how can make work intended?

edit — note when first posted, original question included link jsfiddle seemed relevant example of current question trying achieve, appears work ...


the code in jsfiddle works because there's 1 "i" in code. "i" used in second loop (where functions called) same "i" used in first loop. thus, right answer because second loop running "i" through values 0 through 4 again. if added:

i = 100; functions[0](); 

you'd 100 printed out.

the way introduce new scope in javascript function. 1 approach write separate "function maker" function:

function makecallback(param) {   return function() {     dostuff(param);   }; } 

then in loop:

for (var = 0; < mapinfos.length; i++) {   var x = makecallback(i);   google.maps.event.addlisteneronce(mapinfos[i].map, 'titlesloaded', x); } 

that'll work because call "makecallback" function isolates copy of value of "i" new, unique instance of "param" in closure returned.


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -