Two days ago, when I was blowing water with my colleague, I suddenly talked about closures. This concept is quite understandable, but I feel like I haven’t fully understood it, so I haven’t really understood its use.
concept
Let’s start with the concept of closures
A closure is a function that has access to a variable declared in another function (another scope).
-
Advantages: save variables from external influence, the formation of undestroyed stack variables
-
Disadvantages: Improper use can lead to memory leaks
Analysis of the
Save private variables from contamination
It is easy to understand that there is no outside influence.
Var a = 'foo' function foo() {var a = 'foo' function fo() {console.log(a); } return fo } function f(p) { var a = 'f' p() } f(foo())Copy the code
Answer (click to expand) :
f(foo())
The actual is tofo
As an input parameter to f,fo
The parent function is usedfoo
In a statementa
, so even if foo has been executedreturn
Statement, variablea
Still won’t be destroyedfo
A function is a closure;fo
Function is still used when called from f functionfoo
The a variable defined in the function.
As you can see, the variables are not affected by the redeclaration of assignment after the closure is formed, preventing the variables from being contaminated.
Undestroyed stack memory
To understand undestroyed stack memory, you must first understand the concept of stack memory and the JS memory destruction mechanism
- Stack memoryThe pointer address of the base type and reference type
- Heap memorySave: reference type in
In general, variables stored in stack memory are reclaimed by the JS memory reclamation mechanism after the end of use. For example, variables declared in functions are reclaimed after the return statement or} closing parentheses are encountered.
But in the case of closures, the variables used by the closure are put into the heap and not destroyed as stack memory is reclaimed, thus creating undestroyed variables (actually stored in heap memory)
Improper use can cause memory leaks
When Leader talked with us about performance optimization some time ago, he specifically mentioned not using closures, but he didn’t tell us what problems might be caused by the use of closures.
In fact, the problem is not with closures, but the poor use of closures. As mentioned above, closures can form an undestructible stack memory. Note that “destruct” means that variables in closures will be stored in memory for a long time if you do not release them. As a result, memory space is occupied and performance deteriorates.
> how to do
Simply assign the variable to NULL at the end of the use.
reference
I never understood JavaScript closures until someone explained it to me like this – Juejin.
JavaScript Memory mechanism – Juejin (juejin)