E
enaeher
I would expect this code:
globalFnArray = [];
for (var i = 0; i < 5; i++) { globalFnArray.push (function () { alert
(i) }); }
for (var j = 0; j < 5; j++) { globalFnArray[j](); }
to alert 0, 1, 2, 3, and 4.
Instead, I get 5, 5, 5, 5, and 5 in Firefox, indicating that all of
the functions in globalFnArray are closing over the final value of i
(after the for loop's conditional (i < 5) has failed and the loop has
exited), rather than the value to which i was bound during the
iteration of the loop when the function was defined. This does not
seem consistent with lexical scope as I understand it. Is the for loop
a special case? I'd appreciate any suggestions as to what I'm missing.
Thanks,
--Eli
globalFnArray = [];
for (var i = 0; i < 5; i++) { globalFnArray.push (function () { alert
(i) }); }
for (var j = 0; j < 5; j++) { globalFnArray[j](); }
to alert 0, 1, 2, 3, and 4.
Instead, I get 5, 5, 5, 5, and 5 in Firefox, indicating that all of
the functions in globalFnArray are closing over the final value of i
(after the for loop's conditional (i < 5) has failed and the loop has
exited), rather than the value to which i was bound during the
iteration of the loop when the function was defined. This does not
seem consistent with lexical scope as I understand it. Is the for loop
a special case? I'd appreciate any suggestions as to what I'm missing.
Thanks,
--Eli