Answer the question
In order to leave comments, you need to log in
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; // ...а теперь память очищается
g
and said that there was nothing there - g = null
. The nested function itself remained, no one deleted it. 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
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question