Home  >  Article  >  Web Front-end  >  The meaning of closure in JS

The meaning of closure in JS

一个新手
一个新手Original
2017-09-11 10:34:461215browse


Closure (Closure)

A closure refers to a function that has access to a variable in the scope of another function.

How to create a closure

The most common is to create another function inside a function. Take the TrialFunction() function as an example:

function TrialFunction(property) {

      return function(a, b) {
           var a1 = a[property];           var b1 = b[property];           if (a1 < b1) {                return -1;
           } else if (a1 > b1) {                return 1;
           } else {                return 0;
           }
      };
}

In the above code, the internal function accesses the variable property in the external function. Even if the inner function is returned and called elsewhere, others can still access the property variable.

This situation is because the scope chain of this internal function includes the scope of TrialFunction.

When a function is called, an execution environment (Execution Context) and corresponding scope chain will be created. Subsequently, the function's Activity Object is initialized using the values ​​of arguments and other named parameters. But in the scope chain, the active object of the external function is always in the second place, the active object of the external function of the external function is in the third place, and finally up to the global execution environment as the scope chain.

During function execution, in order to read and write the value of a variable, you need to find the variable in the scope chain.

This mechanism of scope chain leads to a side effect, that is, the closure can only obtain the last value of any variable in the containing function.
For example:

function example() {
   var result = new Array();  
   for (var i = 0; i < 10; i++) 
   {
      result[i] = function() 
      {
         return i;
      }
   }   return result;
}

This function will return an array. Generally, everyone will think that each function should return its own index, that is, [0, 1, 2, ...9]; but in fact Each function returns 10.

The above is the detailed content of The meaning of closure in JS. 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