How does JavaScript closure work in this case and to be more specific: what does the (i) at the end do?
for(var i = 0; i < 10; i++) {
(function(e) {
setTimeout(function() {
console.log(e);
}, 1000);
})(i);
}
Also I’m trying to implement it in my code, and it seems I don’t get it right
for (var i=0; i < len; i++) {
var formID = document.forms["form-" + i];
$(formID).bind("submit", validate);
$(formID).bind("change", function(i){
var divI = '#ind-' + i;
$(divI).css("background-color","green");
})(i);
}
This is a pattern used to create local scope around a variable. If this wasn’t used then every call to
console.log(i)would log the value ofi(10) after the for loop finished.The above is the same as this.
The real problem here is creating functions in a loop. don’t do it 🙂
Your code
But that is wrong, you want to delegate this job to something else.
If you want to get a bit clever you can get rid of these anonymous functions
Edit
Is the same as