Please help me find the reason why the local "j" variable continues to change during the loop:
var a1 = a2 = a3 = {};
for (var i = 1; i < 4; i ++ ) {
(function(j){
console.log(j);
window['a'+j].fu = function(){
console.log('fu:',j);
};
})(i);
}
a1.fu(); // returns "fu:,3" - why not 1?
a2.fu(); // returns "fu:,3" - why not 2?
a3.fu(); // returns "fu:,3"
I read the nice answer on similar issue, but it's not working for my case. Mutable variable is accessible from closure. How can I fix this?