Defining Anonymous Functions In A Loop Including The Looping Variable?
Solution 1:
Wrap the loop block in its own anonymous function:
document.addEventListener('DOMContentLoaded', function()
{
for(var i = 1; i <= 3; i++)
{
(function(i) {
$('a' + i).addEventListener('click', function() {
console.log(i);
})
})(i);
}
}
This creates a new instance of i
that's local to the inner function on each invocation/iteration. Without this local copy, each function passed to addEventListener
(on each iteration) closes over a reference to the same variable, whose value is equal to 4
by the time any of those callbacks execute.
Solution 2:
The problem is that the inner function is creating a closure over i
. This means, essentially, that the function isn't just remembering the value of i
when you set the handler, but rather the variable i
itself; it's keeping a live reference to i
.
You have to break the closure by passing i
to a function, since that will cause a copy of i
to be made.
A common way to do this is with an anonymous function that gets immediately executed.
for(var i = 1; i <= 3; i++)
{
$('a' + i).addEventListener('click', (function(localI)
{
returnfunction() { console.log(localI); };
})(i);
}
Since you're already using jQuery, I'll mention that jQuery provides a data function that can be used to simplify code like this:
for(var i = 1; i <= 3; i++)
{
$('a' + i).data("i", i).click(function()
{
console.log($(this).data("i"));
});
}
Here, instead of breaking the closure by passing i
to an anonymous function, you're breaking it by passing i
into jQuery's data
function.
Solution 3:
The closure captures a reference to the variable, not a copy, which is why they all result in the last value of the 'i'.
If you want to capture a copy then you will need to wrap it in yet another function.
Post a Comment for "Defining Anonymous Functions In A Loop Including The Looping Variable?"