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!
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With