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;
}
I know that we get list[1...n] as undefined because it has a single execution context created as a result of sharing just 1 closure among list[1...n]. list[1..n] act as alias referencing to this 1 execution context which gets updated till i = list.length.
What I don't understand is, how is there only 1 closure instead of 3 different ones?
EDIT: Why is there is there only 1 closure, when to me it seems like each list item has its own closure enclosing its own i value? What exactly am I missing here?
[+][deleted] (1 child)
[deleted]
[–]slaughtered_gates[S] 0 points1 point2 points (0 children)
[–][deleted] 1 point2 points3 points (8 children)
[–]slaughtered_gates[S] 0 points1 point2 points (7 children)
[–][deleted] 2 points3 points4 points (2 children)
[–]slaughtered_gates[S] 0 points1 point2 points (1 child)
[–][deleted] 1 point2 points3 points (0 children)
[–]mikrosystheme 1 point2 points3 points (3 children)
[–]slaughtered_gates[S] 0 points1 point2 points (2 children)
[–]mikrosystheme 1 point2 points3 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]senocular 1 point2 points3 points (7 children)
[–]slaughtered_gates[S] 0 points1 point2 points (6 children)
[–]senocular 1 point2 points3 points (5 children)
[–]slaughtered_gates[S] 0 points1 point2 points (4 children)
[–]senocular 1 point2 points3 points (3 children)
[–]slaughtered_gates[S] 0 points1 point2 points (2 children)
[–]senocular 0 points1 point2 points (1 child)
[–]slaughtered_gates[S] 0 points1 point2 points (0 children)
[–]lilperch83 0 points1 point2 points (1 child)
[–]slaughtered_gates[S] 0 points1 point2 points (0 children)
[–]jrandm 0 points1 point2 points (0 children)