I would like to do the something along the following:
for (var i = 0; i < 10; ++i) {
createButton(x, y, function() { alert("button " + i + " pressed"); }
}
The problem with this is that I always get the final value of i
because Javascript's closure is not by-value.
So how can I do this with javascript?
Note that JSLint doesn't like this pattern. It throws "Don't make functions within a loop.".
Live demo: http://jsfiddle.net/simevidas/ZKeXX/
You need to put the closure into a separate function.
Thise code creates an anonymous function that takes
i
as a parameter for each iteration of the loop.Since this anonymous function has a separate
i
parameter for each iteration, it fixes the problem.This is equivalent to
The anonymous function on the outside is automatically invoked and creates a new closure with
n
in its scope, where that takes the then current value ofi
each time it's invoked.One solution, if you're coding for a browser that uses JavaScript 1.7 or higher, is to use the
let
keyword:From the MDC Doc Center:
Check out the MDC Doc Center for the traditional approach (creating another closure).
Create a new scope for the closure by executing another function:
http://www.mennovanslooten.nl/blog/post/62