Just trying to understand closure vs non-clousure functions. So when I run the following...
function outer()
{
var i = 0;
i++;
console.log( i );
}
outer(); // prints 1
outer(); // prints 1
outer(); // prints 1
But when I run the following ...
function outer()
{
var i = 0;
function inner()
{
i++;
console.log( i );
}
return inner;
}
var closure = outer();
closure(); // prints 1
closure(); // prints 2
closure(); // prints 3
That's fine. I understand the above. However, when I try to run the following ...
function outer()
{
var i = 0;
i++;
console.log( i );
}
var closure = outer();
closure(); // prints 1
closure(); // prints 2
closure(); // prints 3
I get an error because unlike in the closure, the function is not being returned here. So, I modified it to the following ...
function outer()
{
var i = 0;
i++;
console.log( i );
return this;
}
var closure = outer();
closure(); // prints 1
closure(); // prints 2
closure(); // prints 3
I still get an error, only to find out that this
in this context does not refer to the parent function... Rather it refers to the global object. No wonder it gave an error. But what can I replace this
with, to refer to the outer()
function?
Secondly, even then... Will I be able to simulate the closure? I reckon not... But why?