Closures are used in many situations in my work. However, when people ask me what a closure is, I always feel unable to explain why. Therefore, THIS time I am going to comb through the knowledge point of closures to deepen my understanding of closures. It’s also easy to confuse anonymous functions with closures, so let’s make a distinction here. You are welcome to point out the wrong places.
- What is a closure?
- 2. What are anonymous functions
What is a closure?
A function that has access to a variable in the scope of another function – high-level JS. A closure is a combination of a function and the lexical environment in which the function is declared. When an inner function is accessed in a certain way in any of the outer function scopes, a closure is generated — MDN. Closures occur when a function can remember and access its lexical scope, even if the function is executed outside the current lexical scope. How to create: Create a function within a function (as long as you use a callback, you’re actually using a closure). Purpose: Mainly to design private methods and variables. Advantages: Can avoid global variable pollution. Disadvantages: 1. Closures live in memory (closures carry the scope of the function that contains them), which increases memory usage and can easily leak memory if used improperly. Closures can only get the last value of any variable in a function. Features: 1. Function nested function; 2. Internal functions can reference external parameters and variables. 3. Parameters and variables are not collected by garbage collection mechanism; 4. In the execution environment, the scope of a closure includes its own scope, the scope of the containing function, and the global scope; 5. When a function returns a closure that holds the entire variable object, the scope chain of the function’s execution environment is destroyed, but the active objects in the function are stored until the closure is gone. Closures can only get the last value of any variable in a function.
Closure Example 1:
function test(){ var x=10; function foo(){ x*=2; return x; } return foo; Function test(){var x=10; return function(){ x*=2; return x; }; } var y=test(); for(var i=0; i<4; i++){ console.log(y()); //20, 40, 80, 160}Copy the code
Result analysis: The above code is a closure. After the test() function, we return a pointer to the object of function foo — foo(the function is an object; the function name is actually a pointer to the function object). So the variable y is actually a pointer to function foo. But when we call y(), we’re calling foo(), and within function foo(), the variable x can be viewed as a global variable relative to function foo(). So every time foo() is called, the memory of the X object inside the function is not destroyed, so each call to y() will result in twice as much.
Closure Example 2:
function createFunctions() { var result = new Array(); for(var i = 0; i < 10; i++) { result[i] = function() { return i; }; } return result; } var result=createFunctions(); for(var i=0; i<result.length; i++){ console.log(result[i]()); 10/10}Copy the code
Result: Result is an array of 10 functions. Based on the properties of closures, I can be regarded as a global variable of the Resulti function. So after 10 loops, I becomes 10 (the last time I ++ is equal to 10, the loop condition does not hold, but I, as a relative global variable, ends up being 10 in result[I]).
Closure Example 3:
function handler(){ var dom=document.getElementById("test"); dom.onclick=functin(){ process(dom.id); Function handler(){var dom= document.getelementById ("test"); var id=dom.id dom.onclick=functin(){ process(id); } dom=null; }Copy the code
Summary: Whenever you use callbacks in timers, event listeners, Ajax requests, cross-window communication, Web Workers, or any other asynchronous (or synchronous) task, you are actually using closures.
2. What are anonymous functions?
As the name implies, anonymous functions are functions that have no name, are named and allocated space by the compiler, and are usually passed directly as arguments.
The anonymous function has the following form:
Var test=function(){return 20; Function (I){rentun I})(5); Var =testfunction(I){return I; } test(5);Copy the code
The mode of executing a function immediately is to protect the data in the function body from external access and contamination, without leaving a reference to the function in memory.
Difference: An anonymous function is one that does not have a function name specified, whereas a closure has access to a variable in the scope of another function. Anonymous functions are sometimes used in closures. Similarities: Both can design private methods and variables (such as executing functions immediately), and both can avoid global variables contamination.