K
K
Kerrik Sun2021-04-23 00:04:42
JavaScript
Kerrik Sun, 2021-04-23 00:04:42

Closures. Why is the lexical environment of the parent function removed in this case?

Quote from learn.javascript.ru

In the following code, after g becomes unavailable, the lexical environment of the function (and, accordingly, value) will be removed from memory:

function f() { 
  let value = 123; 
  function g() { 
    alert(value); 
  } 
  return g; 
} 
let g = f(); // пока g существует, соответствующее лексическое окружение существует 
g = null; // ...а теперь память очищается


I don't understand why the parent function's lexical environment would be removed from memory. After all, we essentially just cleared the variable gand said that there was nothing there - g = null. The nested function itself remained, no one deleted it.

Or here it means that the line let g = f();contains a call to the parent function, which, when executed, creates a lexical environment. Therefore, by changing the value of the variable to null, we simply remove the call to this parent function? How? What is meant here?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2021-04-23
@Eva25

In the variable g, you write a reference to the function that returned from f (). As long as this reference is available from the global context (via g), the function is kept in memory. All context associated with the function is also preserved, since it is also available from the global context (via g and the function).
By assigning null to a variable, you thereby make the function and its associated context inaccessible from the global context. This means that on the next pass, the garbage collector will remove them as unused.

V
Vladimir, 2021-04-23
@Casufi

In fact, even if you do not assign null, but simply do not use g further in the code, it will also be collected by the collector.
Perfectly described in detail how it works
https://developer.mozilla.org/en-US/docs/Web/JavaS...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question