-2

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.

Sanchit Anand
  • 175
  • 2
  • 10
  • No. `var n = i;` and `console.log(n)` would have worked. `this` is a completely different animal. – Bergi Apr 16 '18 at 18:13
  • Why are you using `this` without calling a constructor? What do you expect to happen? Note that your code will throw in strict mode. And you should be using strict mode. – Jared Smith Apr 16 '18 at 18:15

1 Answers1

0

You can use an arrow function to keep your this:

function g(i){
    return () =>
    {
        console.log(i);
    }
}

for(i=0;i<4;i++)
{
    setTimeout(g(i),3000);
}
Lajos Arpad
  • 45,912
  • 26
  • 82
  • 148