I'm working on closure so hard, and I know that in the loop, new function refer closure using the last value of the iterator
so the following function's result is three times "item3 undefined"
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]();
}
}
and then I know that anonymous function can induce scope, so I edit the first function as:
function buildList(list) {
var result = [];
for (var i = 0; i < list.length; i++) {
(function(){
var item = 'item' + list[i];
result.push( function() {alert(item + ' ' + list[i])} );
})();
}
return result;
}
but the result is "item1 undefined", "item2 undefined", "item3 undefined",
so my question is, why is the result still undefined after I using scope?