Why does this code have two different results?

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 noticed a puzzled place. Then the next step will be shown in this way. Here is where I am really puzzled

+4
source share
4 answers

Because it resultis a function declared as the result of a function call s1. The call s1returns a function s12, and this function uses a variable with a name countthat is declared at a higher level (scope) than itself (this is called a "free variable").

, , โ€‹โ€‹ , "" , , , .

result , count , , , , .

+5

, , . (, , , ) :

s1 :

A) count 0

...

B) , (A) addCount

. , , - , (A) s1. .

, 2- s1 , addEvent, , count, s1, , count, s1.

C) , , (A)

(B), , A s1.

, ?

, s1 , 0 , ( result1).

addCount , , result1, ... .

s1 , addCount , ( 0). , , result2.

addCount, , . result1 ( ), result2, ( ).

+5

addCount .

+1

s1 , .

In addition, your method addCountis global for both calls. The second call cancels the first.

So, in the new method addCount, you have the scope of your second call s1.

So your call addCounthas a second variable countin scope and increments it.

When printing the results, you return to both areas and get the correct values count = 0in the area of โ€‹โ€‹your first call and count = 1in the area of โ€‹โ€‹your second.

0
source

Source: https://habr.com/ru/post/1670437/


All Articles