I have two blocks of code which I believe should produce the same result:
1.
for(var i=0;i<10;i+=1){
var j=i;
setTimeout(function(){
console.log(j);
},100);
}
2.
for(var i=0;i<10;i+=1){
(function(j){
setTimeout(function(){
console.log(j);
},100);
})(i);
}
However, as most of you might expect, the first one log 9 ten times, and the second one log correctly from 0 to 9.
The second one is using closure to preserve the value of i. I think the first one should preserve the value as well, because:
- the
var jcreate a new variable j in each iteration. - current
ivalue is assigned to this newjin the iteration. - this new
jis then bound to thesetTimeout's function in the same iteration. - next iteration will bind a new j to the function in that iteration.
But it turns out that the j is bound to the last i value for all iteration.
So, whats the differences between creating a variable using function argument and var ?
Please point out any mistake ! Thanks in advance !
Thank you all ! I did not know that javascript only has function and global scope ! Blame the other languages who taught me to do so :P