The final part of javascript closures. I do not understand.

Suppose we defined this function in a global scope:

 function createCounter() { var counter = 0; function increment() { counter = counter + 1; console.log("Number of events: " + counter); } return increment; } 

In most examples explaining closure, I see execution:

 createCounter(); 

from a global scope will simply return an internal function:

 function increment() { counter = counter + 1; console.log("Number of events: " + counter); } 

Now this makes full sense because of this line in the createCounter function declaration

 return increment; 

So my question is: why is this:

 var counter1 = createCounter(); counter1(); Number of events: 1 //result 

Finally, for the function to work?

Essentially not counter1 and createCounter both pointers to this internal function that exist in the global scope?

Maybe the best way to ask this is why counter1() works, and not just return an internal function like createCounter ?

+5
source share
4 answers

No, createCounter is a function that returns a separate instance of the increment function containing a new closure with another local variable counter .

So yes, you need an extra call to get a separate instance of the function and call as many times as you like. Note that calling createCounter does not increment the counter, but calling counter1 or counter2 actually incremented it.

 var counter1 = createCounter(); //local counter is still 0 var counter2 = createCounter(); counter1(); // 1 counter2(); // 1 counter1(); // 2 counter2(); // 2 
+3
source

createCounter() returns a function to you without calling it.

You can do createCounter()() to call it without requiring an intermediate variable.

If you also had console output in an external function like this, it would be more clear what happens:

 function createCounter() { console.log("in createCounter"); var counter = 0; function increment() { counter = counter + 1; console.log("Number of events: " + counter); } return increment; } 

When you call createCounter() and save the result in a variable, you get the result "in createCounter", but NOT "Number of events". When you call the function stored in the variable, you get "Number of events: 1", but NOT "in createCounter".

+2
source
  • In JS functions, objects type Function .
  • createCounter is in global scope, but increment not.
  • When you call createCounter (), it returns the function that exists in the 'createCounter function scope and there is another variable counter` in this area.

  • Therefore, when you call the return function called counter1 , like counter1() , it is called, which then increments the counter and writes the result.

+1
source

If you execute console.log(counter1) , it will print the function as it is just a pointer to the function.

When do counter1() , you call the function itself

+1
source

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


All Articles