Consider a simple pattern where we call setTimeout within a loop to print the loop counter:
function g(i){
return function()
{
console.log(i);
}
}
for(i=0;i<4;i++)
{
setTimeout(g(i),3000);
}
This returns the expected result:
0
1
2
3
According to my understanding, this function should do the same thing
function f(i){
this.n = i;
return function()
{
console.log(this.n);
}
}
for(i=0;i<4;i++)
{
setTimeout(f(i),3000);
}
Instead, I get varying results, in NodeJS:
undefined
undefined
undefined
undefined
And in Google Chrome:
3
3
3
3
Neither of these results make sense to me, so I was hoping someone else can explain this to me.