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) :

‘foo’
  1. f(foo())The actual is tofoAs an input parameter to f,
  2. foThe parent function is usedfooIn a statementa, so even if foo has been executedreturnStatement, variableaStill won’t be destroyed
  3. foA function is a closure;
  4. foFunction is still used when called from f functionfooThe 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)