Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code have two different results?

Tags:

javascript

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

like image 404
Rodney_Dian Avatar asked Dec 19 '22 09:12

Rodney_Dian


1 Answers

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.

like image 130
Scott Marcus Avatar answered Dec 21 '22 23:12

Scott Marcus