I study JS at http: //learn.javascript/ , now I am reading the subsection “Closing a function from the inside” in the section “Closures, scope”.
The “Return Function” item describes an example with a nested function.

Actually, I don’t understand how counter every time it starts recalls the currentCount variable, considering what is written in the same section, that LexicalEnviroment is erased from memory every time the function is completed, and every time it is started again it is created anew.

I do not understand where currentCount is stored, if the lexical environment is erased every time?

    1 answer 1

    Such questions cause me a mean tear on the beard.

    It's simple - LexicalEnvironment really destroyed after the call ends.
    But in the example, the work is not finished, makeCounter returned function retains a reference to the parent [ makeCounter ] variable object.

    That is, as long as the returned function is alive, the parent LE must persist, all of a sudden it needs to refer to the parent function for the variables (what happens: there is no currentCount variable in the returned function)?

    Garbage collectors work on the algorithm of links (Mark and sweep), in general, it is something like this:

    • There are roots, that is, that which will always exist (in browsers it is a window object, and it cannot be deleted).
    • After each awakening, he [the collector] recursively goes around the roots and marks everything he can reach; It is considered as necessary and useful. Everything else is considered unattainable and the memory from under them is returned to the environment.

    And now remember that the returned function, conditionally stored in a window , refers to the parent LexicalEnvironment via the hidden [[Scope]] property.
    The builder simply cannot delete it - window -> counter -> [[Scope]] .

    This explains why the new makeCounter call created a pristine- makeCounter counter — every function call gives it a crystal new LexicalEnvironment .


    Closures are generally a very interesting thing, which can be very powerful, and can be confusing to the end, if you don’t know the principles of how closures work.