Predicting Execution Context Output - Object-Oriented JavaScript

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

How does the lookup process work in case of anonymous functions?

I was confused applying this analogy to the following snippet :

function buildList(list) {
var result = [];
for (var i = 0; i < list.length; i++) {
var item = 'item' + i;
result.push( function() {console.log(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() //logs "item2 undefined" 3 times

prasannahegde
welcome to shbcf.ru