Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to fix this Javascript closure

I have been familiarizing myself with javascript closures and ran across this article http://blog.morrisjohns.com/javascript_closures_for_dummies.html

Due to the closure, Example 5 does not work as expected. How would one modify

result.push( function() {alert(item + ' ' + list[i])} );

to make the code work?

function buildList(list) { 
  var result = [];
  for (var i = 0; i < list.length; i++) {
    var item = 'item' + list[i];
    result.push( function() {alert(item + ' ' + list[i])} );
  }
  return result;
}

function testList() {
  var fnlist = buildList([1,2,3]);
  // using j only to help prevent confusion - could use i
  for (var j = 0; j < fnlist.length; j++) {
    fnlist[j]();
  }
}

testList();

Thanks!

like image 740
sujoe Avatar asked Dec 28 '22 10:12

sujoe


1 Answers

function buildList(list) { 
  var result = [];
  for (var i = 0; i < list.length; i++) {
    (function(i) {
      var item = 'item' + list[i];
      result.push(function() {
        alert(item + ' ' + list[i]);
      });
    })(i);
  }
  return result;
}
like image 103
Alex Wayne Avatar answered Jan 15 '23 10:01

Alex Wayne