behavior of javascript 'this' keyword in closure : <p>Consider a simple pattern where we call setTimeout within a loop to print the loop counter: </p>

<pre><code>function g(i){
    return function()
    {
        console.log(i);
    }
}

for(i=0;i&lt;4;i++)
{
    setTimeout(g(i),3000);
}
</code></pre>

<p>This returns the expected result:</p>

<pre><code>0
1
2
3
</code></pre>

<p>According to my understanding, this function should do the same thing</p>

<pre><code>function f(i){
    this.n = i;
    return function()
    {
        console.log(this.n);
    }
}

for(i=0;i&lt;4;i++)
{
    setTimeout(f(i),3000);
}
</code></pre>

<p>Instead, I get varying results, in NodeJS:</p>

<pre><code>undefined
undefined
undefined
undefined
</code></pre>

<p>And in Google Chrome: </p>

<pre><code>3
3
3
3
</code></pre>

<p>Neither of these results make sense to me, so I was hoping someone else can explain this to me.</p>
