function makeCounter() {
var i = 0;
return function() {
console.log( ++i );
};
}
var counter = makeCounter();
counter(); // logs: 1
counter(); // logs: 2
why the result of counter() invoked the second time is '2' but not '1'?
I try to find out its executing processes, so I rewrite makeCounter():
function makeCounter() {
var i = 0;
console.log('outer');
return function() {
console.log('inner');
console.log( ++i );
};
}
var counter = makeCounter();
counter();
counter();
and result is:
outer
inner
1
inner
2
Can I think that: i is the argument of function counter(), the first counter() executed, i changes to '1'. So the second counter() executed, i is '2'.