Self executing anonymous functions are used to solve the problem of using closures in the for loop
- 2020-03-30 03:55:41
- OfStack
This code outputs 10 tens instead of the expected 0 to 9, because inside the closure is a reference to I, and then by the time the function executes I has become 10
function f1(){
for(var i = 0; i < 10; i++) {
setTimeout(function() {
alert(i);
}, 1000);
}
}
f1();
The above problems can be solved by using self-executing anonymous functions
function f2(){
for(var i = 0; i < 10; i++) {
(function(e) {
setTimeout(function() {
alert(e);
}, 1000);
})(i);
}
}
f2();
The anonymous function here takes I as an argument, the e here has a copy of I, and the reference is a reference to e, which avoids the above problem