7.2 Closures
Definition: A closure refers to a function that has access to a variable in another function scope.
Understanding closures:
- Scope chain: When a function is called, an execution environment and the corresponding scope chain are created. In a scope chain, an external function's active object is always in the second place, and the outer function's outer function's active object is in third place .... Until the global execution environment as the end of the scope chain
- Variable object: The Variable object of the global function always exists, while the variable object of the local environment exists only in the process of function execution.
- In general, when the function is finished, the local active object is destroyed, only the global scope (the variable object in the global execution environment) is saved in memory, but the case of the closure is different.
- A function object defined inside another function adds the active object containing the function (that is, an external function) to its scope chain.
- The corresponding closure, after the execution of the external function, its active object is not destroyed, because the scope chain of the anonymous function is still referencing the active object. That is, after the external function returns, the scope chain of its execution environment is destroyed, but its active objects remain in memory until the anonymous function is destroyed and its active object is destroyed.
- Because the closure carries the scope of the function that contains it, it consumes more memory than the other functions
Side effects of closures:
- Closures can only get the last value that contains any variable in the function. Because the closure holds the entire variable object, not a particular variable.
function Createfunctions () { var result = new Array (); for (var i=0; i<10; i++) { Result[i] = function () { return i; }; } return result;}The above function returns an array of functions, but each of its functions will return 10. Because the active objects of the createfunctions () function are kept in the scope chain of each function, they refer to the same variable i
- Improved method:
function Createfunctions () { var result = new Array (); for (var i=0; i<10; i++) { Result[i] = function (num) { return function () { return num; }; } (i); } return result;}Create another anonymous function to force the behavior of the closure to conform to expectations.
In this way, each function in the result array has its own copy of the NUM variable, so you can return different values.
JavaScript Advanced Programming Chapter 7th function expressions