The problem is within the variable i, which is been bound to the same variable which is outside the function. So, we need to bind the variable to each function with a separate and unchanging value like this:
var funcs = [];
function createfunc(i) {
return function() {
console.log("My value: " + i);
};
}
for (var i = 0; i < 3; i++) {
funcs[i] = createfunc(i);
}
for (var j = 0; j < 3; j++) {
// and now let's run each one to see
funcs[j]();
}
I hope this will help.
Want to know more about Java? Prefer this tutorial on Java Tutorial.
Want to become a Java Expert? Join Java Course now!!