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?