Closures and their pros and cons

1. The concept of closure

Popular understanding: closure is a function that can read the internal variables of other functions;
closure = inner function + referenced outer function variable ; that is, the inner function refers to the variable of the outer function to form a closure.
Closure function : Closure can protect the private variables of the function from external interference, save the reference of the upper scope, and realize the privatization of methods and properties .
A common way to create a closure: nest a function inside a function , and the inner function refers to the variables defined in the outer function ; as shown in the following figure:

//闭包 1: 2-5 行构成一个闭包
1  function outer() {
    
    
2              let name = 'andy';
3              return function() {
    
    
4                 console.log(name);
5              }
6          } outer()();

//闭包 2: 2-6 行构成一个闭包 
1  function outer() {
    
    
2              let name = 'andy';
3              function inner() {
    
    
4                  console.log(name);
5             }
6              inner();
7          }
8          outer();

2. Advantages and disadvantages of closures

advantage:

  1. Avoid global pollution;
  2. Variables are stored in memory for a long time; in the function body, as the function is executed each time, the object defined inside the function (if not referenced by the closure function) will be destroyed; if it is referenced by the closure, it will be retained. Therefore, the existence of the closure causes the variables not to be destroyed, but retained, and thus stored in memory for a long time;

shortcoming:

  1. Memory leak (consumption) : The memory that is no longer used in the application, for some reason, cannot be released in time, resulting in a memory leak.
    The existence of closures prevents certain variables from being destroyed in time, and memory cannot be released in time, which leads to memory leaks. But the existence of closures does not necessarily lead to memory leaks. The memory leak caused by the closure only exists in the IE browser, and it will not cause the memory leak in other browsers.
  2. Permanent memory, increasing memory usage : This memory waste is not only because it is resident in memory, but more importantly, improper use of closures will cause invalid memory;
  3. Performance issues : When using closures, cross-scope access is involved, and each access will result in performance loss;

3. Closure application scenarios

  1. achieve modularity;
  2. Realize the private encapsulation of variables;
  3. implement iterator;

4. When this encounters a closure

In non-strict mode, generally speaking, this in the closure points to window, and in strict mode, this in the closure is undefined;

var  uname  =  "window"; 
var  object = {
    
                 
    		uname : "object",
    		fun: function() {
    
                     
        			console.log(this.uname);  // object  由 Object对象调用,this 指向 Object          
        			return  function() {
    
                        
           				console.log(this.uname);  //window   闭包 普通函数调用,指向 window      
        			}             
    			} 
} 
object.fun()();

5. Closure destruction

After the module or application is executed, just assign the inner function to null , such as inner( ) = null;

6. Common misunderstandings of closures

  1. The closure must have return to return the function (wrong) ;
    the closure in the figure below does not contain return, so return is not a necessary condition for forming a closure.
//闭包 2: 2-6 行构成一个闭包 
1  function outer() {
    
    
2              let name = 'andy';
3              function inner() {
    
    
4                  console.log(name);
5             }
6              inner();
7          }
8          outer();
  1. Closures must cause memory leaks (wrong).
    Only closures in IE browsers may cause memory leaks, and other browsers will not. Closures may cause memory leaks, but not necessarily.

7. Debugger view closure

Take Google Chrome as an example:

  1. break point, page refresh
    Please add a picture description
  2. Click the step button to view the code execution sequence. When the code runs to line 14, it will display Closure (outer), which is the closure.
    insert image description here

Recommended articles for reference:

  1. Correct understanding of closures
  2. The impact of scope on performance;

Guess you like

Origin blog.csdn.net/qq_45050686/article/details/126925356