What is the correct way to fix this Javascript closure

Posted by sujoe on Stack Overflow See other posts from Stack Overflow or by sujoe
Published on 2011-11-22T17:14:45Z Indexed on 2011/11/22 17:51 UTC
Read the original article Hit count: 150

Filed under:
|

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!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about closures