After reading around in SO and this good article, I still quite didn't understand the scope of local variables. I also read this good article from Ben Alman.
function foo(){
var i=0;
console.log(++i);
}
foo(); //1
foo(); //1
//##################
var foo = function(){
var i=0;
console.log(++i);
};
var x = foo;
x(); //1
x(); //1
//##################
function foo2(){
var i = 0;
return function(){
console.log(++i);
};
}
var x = foo2();
x(); //1
x(); //2 -- I don't get this
Why on the third example, it seems that I can have a singleton function, with the same common internal variable after calling it several times, even if it calls i=0
?