What is the correct way to fix this Javascript closure
- by sujoe
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!