Mind map
closure
Before understanding closures, let's learn about the memory release of the parent scope and stack.
Concept of parent scope
- Where is the parent scope of a function created and who is the parent scope
var a = 10 function foo(){ console.log(a) } function sum() { var a = 20 foo() } sum() /* output 10 / Copy code
The function foo() is created globally, so the parent scope of a is window and the output is 10
Thinking questions
var n = 10 function fn(){ var n =20 function f() { n++; console.log(n) } f() return f } var x = fn() x() x() console.log(n) /* output * 21 22 23 10 / Copy code
Idea: what is the return value of fn? The variable x is what. Here, the return value of fn is the function name F, that is, the heap memory address of F. x() means that the function f() is executed instead of fn(). The output result is obvious
- About how to find parent scopes
reference resources: Thoroughly solve the interview questions of JS variable promotion
JS stack memory free
-
Heap memory: stores reference type values, object types are key value pairs, and functions are code strings.
-
Heap memory release: assign the spatial address variable of reference type to null, or the browser will release this address when no variable occupies heap memory
-
Stack memory: provides the environment for code execution and stores basic type values.
-
Stack memory release: generally, the private scope of the function will be released after the function is executed.
However, there are special cases for the release of stack memory: ① after the function is executed, but there are contents in the private scope of the function that are still used by variables outside the stack, the stack memory cannot be released, and the basic values inside will not be released. ② The stack memory in the global environment will only be released when the page is closed
What is a closure
Definition of closure in JS Ninja script (P90): closure allows functions to access and operate variables outside functions. The definition of closure in the Red Book: closure refers to a function that has the right to access variables in the scope of another function. MDN defines closures as: closures refer to functions that can access free variables. The free variable here is the variable in the scope of the external function.
In summary, a closure is a function that has access to a variable in the scope of another function
Reasons for closures
If the internal function has a reference to the external scope, it will lead to closure. In fact, there is an example of closure from the concept of parent scope introduced above. return f is an expression.
var a = 0 function foo(){ var b =14 function fo(){ console.log(a, b) } fo() } foo() Copy code
There are references a and B of the external scope in the sub function fo memory, so this will produce closures
Function of closure
- Protect the private variables of the function from external interference. Form stack memory that is not destroyed.
- Save, save the values in some functions. Closures can privatize methods and properties
Closure classic usage scenario
-
- return returns a function
var n = 10 function fn(){ var n =20 function f() { n++; console.log(n) } return f } var x = fn() x() // 21 Copy code
return f, f() here is a closure, and there is a reference to the superior scope.
-
- Function as parameter
var a = 'Lin 11' function foo(){ var a = 'foo' function fo(){ console.log(a) } return fo } function f(p){ var a = 'f' p() } f(foo()) /* output * foo / Copy code
Use return fo to return. fo() is the closure. The parameter f(foo()) executes is the function fo. Because the parent scope of a in fo() is the function foo(), the output is foo
-
- IIFE (self executing function)
var n = 'Lin 11'; (function p(){ console.log(n) })() /* output * Lin 11 / Copy code
It also generates the closure p(), which exists in the reference n under the window.
-
- Cyclic assignment
for(var i = 0; i<10; i++){ (function(j){ setTimeout(function(){ console.log(j) }, 1000) })(i) } Copy code
Because of the existence of closures, the above can output 1 ~ 10 in turn, and closures form 10 private scopes that do not interfere with each other. After removing the outer self executing function, there is no reference to the external scope, and the output result is 10 consecutive. Why is 10 continuously output? Because JS is single threaded, asynchronous code will not be executed first (will be put on the stack). Asynchronous code will not start to execute until i + + to 10 of synchronous code is executed. At this time, i=10 and 10 are output.
-
- Using callback functions is using closures
window.name = 'Lin 11' setTimeout(function timeHandler(){ console.log(window.name); }, 100) Copy code
What should I pay attention to when using closures
It is easy to cause memory leakage. Closures carry the scope of other functions, so they occupy more memory than other functions. Overuse of closures can lead to excessive memory consumption, so use closures with caution.
Classic interview questions
- for loops and closures (so-called must brush questions)
var data = []; for (var i = 0; i < 3; i++) { data[i] = function () { console.log(i); }; } data[0](); data[1](); data[2]() /* output 3 3 3 / Copy code
i here is the global i, sharing a scope. When the function is executed, i=3, resulting in the output structure of 3.
- Use closures to improve the above writing method to achieve the desired effect. Writing method 1: self executing functions and closures
var data = []; for (var i = 0; i < 3; i++) { (function(j){ setTimeout( data[j] = function () { console.log(j); }, 0) })(i) } data[0](); data[1](); data[2]() Copy code
- Writing 2: use let
var data = []; for (let i = 0; i < 3; i++) { data[i] = function () { console.log(i); }; } data[0](); data[1](); data[2]() Copy code
let has a block level scope, and the three private scopes formed do not interfere with each other.
I am currently engaged in on-the-job front-end development. If you also want to learn the front-end development technology now, you will encounter any questions about learning methods, learning routes, learning efficiency, etc. in the process of learning the front-end. This set of interview questions covers almost all the knowledge points of the front-end. You can be interested Click here to get~
n () {
console.log(i);
};
}
> `let` It has a block level scope, and the three private scopes formed do not interfere with each other. > I am currently engaged in on-the-job front-end development. If you also want to learn the front-end development technology now, you will encounter any questions about learning methods, learning routes, learning efficiency, etc. in the process of learning the front-end. This set of interview questions covers almost all the knowledge points of the front-end. You can be interested[Click here to get](https://gitee.com/vip204888/web-p7)~