What is js closure

Definition: A closure is a function that can read variables inside other functions. In javascript, only sub-functions inside a function can read local variables, so closures can be understood as "functions defined inside a function". In essence, a closure is a bridge that connects the inside of a function with the outside of a function. (The most typical application of a closure is to implement a callback function (callback)).

Closure instance

function foo(a) {
  var b = a + 1;
  function bar(c) {
    console.log(a, b, c);
  }
  return bar;
}
let result = foo(1);
result(3);
//控制台打印1,2,3

We can see from the above example. The function bar is nested in the function foo, and then running foo returns the bar function, and then running the result of calling foo actually executes bar, and finally the bar function will execute and output 123

In fact, the above example actually creates a closure, because the variable result outside the function foo refers to the function bar inside the function foo. That is, when the inner function bar of function foo is referenced by a variable outside function foo, a closure is created.

What's the use of closures?

In short, the function of the closure is that after foo finishes executing and returns, the closure prevents Javascript's garbage collection mechanism from recovering the resources occupied by foo, because the execution of foo's internal function bar depends on the variables in foo. 

In the above example, due to the existence of the closure, after the function foo returns, c in bar always exists, so that every time result(3) is executed, the function bar accepts 3 and then outputs a, b, c

Then let's imagine another situation, if foo does not return the function bar, the situation is completely different. Because after foo is executed, bar is not returned to the outside world of foo, but is only referenced by foo, and at this time, foo will only be referenced by foo, so functions a and b refer to each other but are not disturbed by the outside world (referenced by the outside world) , the functions foo and bar will be recycled.

Application scenario

  1. Access variables inside functions

  1. keep variables in memory

Disadvantages and solutions of closures

  • After the function is executed, the local variables in the function are not released, and the memory usage time will become longer

  • prone to memory leaks

solve

If you can use it, don’t use it, or use it to set it to null

Guess you like

Origin blog.csdn.net/weixin_56661658/article/details/128749434