Possible Duplicate:
Javascript closure inside loops - simple practical example
I was trying to code something similar to this :
var funcs = [];
for (var i=0; i<5 ; ++i) {
funcs[i]=function() {
alert(i);
};
}
Obviously, calling funcs[0]
won't alert 0
as expected, simply because the variable i
is captured by the anonymous function, and calling any of funcs[0..4]
will alert '4' (the value of i
after the last iteration and shared by all created functions).
The first work around that comes to my mind is using some kind of function generator :
var funcs = [];
for (var i=0; i<5 ; ++i) {
funcs[i]=(function(cap) {
return function() {alert(cap)};
})(i);
}
This do the trick, but seems really puzzling and hard to read. Is there any better way to get the intended behavior without using a function wrapper?