Here my intent is to iterate over an array of elements, and set an event handler on each element while also binding the current iterator value to that event handler. What I’ve come up with is:
for (var i = 0; i < elementArray.length; ++i)
{
var elem = elementArray[i];
elem.onmouseover = function() { foo(i); }
}
function foo(index)
{
alert(index);
}
Here I use a closure to bind i to foo. The problem is that when foo is actually invoked, i is always equal to elementArray.length, because of course, when foo is invoked i has already been incremented to the maximum value. What I want here, I think, is for a new copy of i to be bound to each anonymous function, so that it passes the correct value to foo. But I’m not sure what the best way to do this is.
This isn’t working for you because by the time the
mouseoverhandler is invoked, the value ofihas changed, it is equal toelementArray.length. What you should do instead is return a function which creates a closure and holds the value ofiat the time it is defined.