Possible Duplicate:
Javascript closure inside loops – simple practical example
Rather than explaining the question, I’ll give an example:
for (var i = 0; i < 100; i ++) {
get_node(i).onclick = function() {
do_something_very_important(i);
}
}
Is there any way to have the value of i substituted into the function upon creation rather than execution? Thanks.
Yes, you can, but that won’t work for the example you provided. You would be having a very common closure problem in that
forloop.Variables enclosed in a closure share the same single environment, so by the time the
onclickcallback is called, theforloop will have run its course, and theivariable will be left pointing to the last value it was assigned. In your example, thedo_something_very_important()function will be passed the value100for each node, which is not what you intend.You can solve this problem with even more closures, using a function factory:
This can be quite a tricky topic, if you are not familiar with how closures work. You may want to check out the following Mozilla article for a brief introduction:
UPDATE:
You could also inline the above function factory as @adamse suggested in the other answer. This is actually a more common approach, but is practically the same as the above:
Any yet another solution is to enclose each iteration in its own scope, by using self invoking anonymous functions: