Simple Javascript Closure Issue -


this question has answer here:

i know why doesn't work, can't find correct way of doing it.

i'm trying build object using loop. object builds fine, when try use callback, alerts "2" each person, i'd alert position in array.

var playerarr = ["steve", "paul", "bob"];  var myautomatedobj = {}; (var i=0; i<playerarr.length; i++){     var objname = playerarr[i];     myautomatedobj[objname] = {};     myautomatedobj[objname]["callback"] = function(){         alert(i);     } }  //returns incorrect alert myautomatedobj.steve.callback(); 

the property i referenced each function, because it's in scope, value equals length of array @ end of loop.

try following:

myautomatedobj[objname]["callback"] = (function(j) {     return function(){         alert(j);     } })(i); 

this way copy value , no longer referencing variable named i.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -