I just saw a question regarding closures in JavaScript regarding code similar to the following:
for (i=0;i<n;i++){ foo.bind( function() { bar(i); } ); }
The question was why does every closure execute bar(i) with i as the value of n for every instance, rather than whatever the value of i was when the closure was defined. He had reckoned that i was being passed by reference than by copy and found that making a copy of i in a variable local to the closure solved the problem.
But what he’s really done is confused a closure with an eval() statement. If he had written the code similar to eval(“function(){bar(“+i+”);”); he would have gotten what he wanted. The difference being that when you use eval() the variable i is determined when the eval() is executed. But with a closure, i is determined when the closure is executed, and every time the closure is executed.
It’s also important to note that the i referenced inside the enclosure is not a reference to the i in the outer loop, rather it actually IS the same i in the outer loop. No parameter passing is going on.
One other possible solution is to define the closure to take a parameter, and pass i in as a parameter to the enclosure:
for (i=0;i<n;i++){ foo.bind( function(x) { bar(x); } )(i); }