Oh no, the closure issue strikes once more! The problem lies in the fact that a function defined within a loop only recognizes the variable named i
('closures' around it) but doesn't know the exact value of i
at that specific moment of definition. If you search for the closure issue
, you'll come across many similar occurrences here on SO. They all share a common thread: a function is defined (as an event handler or timeout callback) within a loop, and that function somehow interacts with the loop variable (or a value derived from it).
An effective solution to this issue involves explicitly localizing the loop variable for the function. Here's an example:
b[i] = (function(i) {
return { text: temp[i], onclick: function(){alert(temp[i])}};
})(i);
Explanation: during each iteration of the loop, you create and immediately execute a function that takes the current value of i
as an argument. Consequently, the function it generates (as an onclick
handler, in this scenario) no longer operates on the 'closured' i
but instead uses a localized one.
Wrapping a function definition within another function serves as a general remedy for such issues. However, in this particular case, there may be room for optimization:
b[i] = (function(tempVal) {
return { text: tempVal, onclick: function(){alert(tempVal)}};
})(temp[i]);
... since you solely manipulate the temp[i]
value here, without any reliance on i
itself.