4 ms·
For those who wonder how useful JavaScript closures can be. They are very useful. Take a simple pattern. You are iterating through a statement, and you want to
by csomar 15y ago
For those who wonder how useful JavaScript closures can be. They are very useful. Take a simple pattern. You are iterating through a statement, and you want to use the variable i of the statement in another function.
for (var i = 0; i < 5; i++) {
console.info(i);
}
This works fine. And the console displays 1, 2, 3 and 4. But let's suppose that you have the following code:
for (var i = 0; i < 5; i++) {
$(DOMelement:eq(i)).click(function() {
console.info(i);
});
}
The console will always display "4" whichever DOMelement you clicked. Surprise? That's because it calls i which holds 4. JavaScript passed the argument by reference to i and by the time you clicked, the iterations already finished.
JavaScript closures help solve this problem (Luckily). Here is how:
for (var i = 0; i < 5; i++) {
$(DOMelement:eq(i)).click(function() {
return function() {
console.info(i);
}
});
}
That's because JavaScript returns now a new function for each DOM element. Each new function holds the i value while iteration and now the final value.
- anc2020 15y agoI'm not sure your code does as intended, won't the function be called only once the element is clicked? This should work okay: for (var i = 0; i < 5; i++) { $(DOMelement:eq(i)).click((function(i) { return function() { console.info(i); } }(i))); } Also surely DOMelement.eq(i) as opposed to DOMelement:eq(i)?
- sdevlin 15y agoI think you're correct. His interior function is still just another closure around the original var i. Also, this feels like piling on, but I think the original (intentionally erroneous) example would print '5' repeatedly rather than '4'. var i ends up with the value 5.
- csomar 15y agoYes, you are correct (I can't edit right now). You need to return a new function, and a reference actually. for DOM part, I didn't understand your question. However, the right way to do it is $(DOMelement:eq(i)).each(); to iterate through each element.