Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
76
rated 0 times [  79] [ 3]  / answers: 1 / hits: 18948  / 16 Years ago, fri, march 13, 2009, 12:00:00

I am very puzzled about this code:


var closures = [];
function create() {
for (var i = 0; i < 5; i++) {
closures[i] = function() {
alert("i = " + i);
};
}
}

function run() {
for (var i = 0; i < 5; i++) {
closures[i]();
}
}

create();
run();

From my understanding it should print 0,1,2,3,4 (isn't this the concept of closures?).


Instead it prints 5,5,5,5,5.


I tried Rhino and Firefox.
Could someone explain this behavior to me?


More From » loops

 Answers
35

Fixed Jon's answer by adding an additional anonymous function:



function create() {
for (var i = 0; i < 5; i++) {
closures[i] = (function(tmp) {
return function() {
alert(i = + tmp);
};
})(i);
}
}


The explanation is that JavaScript's scopes are function-level, not block-level, and creating a closure just means that the enclosing scope gets added to the lexical environment of the enclosed function.



After the loop terminates, the function-level variable i has the value 5, and that's what the inner function 'sees'.






As a side note: you should beware of unnecessary function object creation, espacially in loops; it's inefficient, and if DOM objects are involved, it's easy to create circular references and therefore introduce memory leaks in Internet Explorer.


[#99849] Sunday, March 8, 2009, 16 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rylee

Total Points: 658
Total Questions: 114
Total Answers: 116

Location: Christmas Island
Member since Mon, Oct 19, 2020
4 Years ago
;