I have the below function which always results me 5. I see that the function inner is getting executed in the global context, so the result is 5 always.
I tried to wrap the entire loop inside a closure, so that it creates a new scope yet it failed.
var myAlerts = [];
for (var i = 0; i < 5; i++) {
myAlerts.push(
function inner() {
alert(i);
}
);
}
myAlerts[0](); // 5
myAlerts[1](); // 5
myAlerts[2](); // 5
myAlerts[3](); // 5
myAlerts[4](); // 5
Can anyone tell me on how to fix this scoping issue here?
Try closures:
for (var i = 0; i < 5; i++) {
(function(i){
myAlerts.push(
function inner() {
alert(i);
}
);
})(i);
}
Wrapping the function in a closure works:
var myAlerts = [];
for (var i = 0; i < 5; i++) {
myAlerts.push((function(i) {
return function inner() {
alert(i);
}
})(i));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With