Home  >  Article  >  Web Front-end  >  What is closure

What is closure

一个新手
一个新手Original
2017-09-08 13:12:501498browse

What is a closure:

A closure refers to a function that has access to a variable in the scope of another function.
–《Javascript Advanced Programming》

在这个函数fun2中可以访问另一个函数中的变量a,所以fun2()就是一个闭包。
function fun1 () { 
      var  a = 0; 
      function fun2 () {  
          console.log(a);  
      } 
      fun2(); }

1. Call the closure method outside the defined function, escape method:

  (1). The function is assigned to a global variable;

var globalVar; function outer() { 
      console.log(‘outer’); 
      function inner(){ 
          console.log(‘inner’); 
      } 
      globalVar = inner;       
      } outer(); // outer 
      globalVar(); // inner;

In this example inner() successfully escapes through the reference of the global variable, and can now be called globally, and can refer to the variable of outer()

  (2). 'Rescue' the reference of the inner function by returning the value

function outer() { 
      console.log(‘outer’); 
      function inner(){ 
          console.log(‘inner’); 
      }    
      return inner;       
      } 
      var fn = outer(); // outer 
      fn(); // inner;

In this example inner() escapes successfully by returning the value, and now it can be Called globally, and can refer to variables of outer()

2. The impact of calling closures outside the function: increased memory usage;

Under normal circumstances, the function is after the function call ends The execution environment leaves the environment stack, the defined variables are discarded (disposal is related to the garbage collection mechanism), the active variables (variable objects) will be destroyed, and the memory will be released. But now because the scope chain of the closure includes the variable object of the external function, the variables of the external function may be referenced again. The garbage collection mechanism will not discard the variables of the external function, and the variable objects of the external function are retained in the memory. This increases the memory usage.

3. The relationship between closures and variables: Common misunderstandings and solving techniques in closures

Closures save the entire variable object containing the function, and the external object variables obtained are closure The object variable at the time the package is called is usually the last value of the external function variable.

Example:

function createFun() { 
      var result = []; 
      for ( var i = 0; i < 10; i++) { 
          result[i] = function() { 
              return i; 
          }; 
      } 
      return result; } var result = createFun(); console.log(result5); // 10

The return value of the external function here is an array, and the array values ​​are references to different functions (closures). We will mistakenly think that each closure The return values ​​of the package calls are different, but in fact each function returns the same value. Because when the closure is called, the external function that called the closure has been executed. At this time, i = 10 in the variable object of the external function, and the return value of our closure is i, the closure will obtain the external variable object at the time of the call. , i at this time is 10.

Solution:

function createFun() { 
      var result = []; 
      for ( var i = 0; i < 10; i++) { 
          result[i] = function(num) { 
              return function() { 
                     return num; 
              }; 
           }(i); 
      } 
      return result; } var result = createFun(); console.log(result5); // 5

In the loop, we define an anonymous array and assign the result of immediately executing the anonymous function to the array. The anonymous function here is A parameter num, each time i is passed as a parameter to num, each time num is looped, a different value will be obtained, so a different function is returned each time (the difference is that the num value is different), when the array value is called externally, it will be returned Different values, as expected.

4. Pay attention to the this value in the closure

First of all, regarding the this point in the function, we should know that this points to the object that calls the function. If there is no explicit calling object, it points to the window object.

It is easy to mistake the this point in the closure, for example:

var name = “window”; 
      var o = { 
          name: “object”, 
          getName: function() { 
              return function() { 
                  return this.name; 
              }; 
          } 
      }; console.log(o.getName()()); // window

It can be seen that the closure this points to the global object. After analysis, you can put o.getName ()() is written as (o.getName())(). This expression is equivalent to executing o.getName() in the first step. This function returns an anonymous function (closure) and then executes it globally. This closure is not called through object o, so this points to the global object.

5. The problem of memory leaks, how to reduce unnecessary memory usage

function assignHandler() { 
          var ele = documnet.getElementById(“somenode”); 
          ele.onclick = function() { 
              console.log(ele.id); 
          }; 
          }

In the above example, the method of defining ele is related to the anonymous function, so ele is saved has a reference to the anonymous function, and the closure will reference the containing function and also reference the ele object, which will cause a circular reference to the object. The ele element (the DOM element takes up a large amount of memory) will always be saved in the memory and cannot be released. The solution The method is as follows:

function assignHandler() { 
          var ele = documnet.getElementById(“somenode”); 
          var id = ele.id; 
          ele.onclick = function() { 
              console.log(id);    // 通过id值中介表面上解除了与ele的循环引用 
          }; 
          ele = null; // 手动解除引用 }

The above is the detailed content of What is closure. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn