var addCount;
function s1() {
var count = 0;
addCount = function() {
count++;
};
function s12() {
console.log(count)
}
return s12
}
var result1 = s1();
var result2 = s1();
addCount();
result1(); // count = 0;
result2(); // count = 1;
In the picture I marked the puzzled place Then, the next step will be shown in this way This is where I am really puzzled
Because result
is a function that is declared as being the result of calling the s1
function. Calling s1
returns the s12
function and that function uses a variable called count
which is declared at a higher level (scope) than itself (this is called a "free variable").
When a free variable is used inside of a function that has a lifetime that is longer than the function where the free variable was declared, a "closure" is created around that free variable and it stays in scope even after the function it was declared in terminates.
When you call result
the first time, count
increases by one and that value stays in memory so that when you call it a second time, you are working with the last value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With