5. Closure
Closure means that the inner function can reference the variables in the function that enclose it, even if the execution of the outer function is terminated.
Let's look at a closure example first.
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Code ① Is in the inner layer of the function, but it can use the variable num of the outer layer.
Closing also solves another common Js problem and the impact of global variables.
By automatically executing the anonymous function combination closure, you can hide the original global variables. See the following example:
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
The closure is often used when setTimeout is used.
<Html> <pead> <title> demo </title> <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8 "/> </pead> <body> CssRain </body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Using setTimeout () in this way can avoid some problems.
Of course, using closures also causes some problems. The following code is used:
<Html xmlns = "http://www.w3.org/1999/xhtml"> <pead> <title> demo </title> <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8 "/> </pead> <body> <ul id =" abc "> <li> AAA </li> <li> BBB </li> <li> CCC </li> </ul> </body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Click the serial number 3 in the pop-up window of li. It is not the correct serial number. The referenced value is the last value assigned.
We can use the following code to solve the problem:
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
By using closures to control the scope, we can meet our requirements.
The above code can be divided:
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
The concept of closure is not easy to grasp. I also spent a lot of time and effort to understand it.
6. Summary
Notes (2), (3), and (4) explain several important content in JavaScript, including references, function overloading, scopes, context objects, and closures.
Key content of a reference: pointer, array reference, string reference, difference, value passing, and address passing.
Key Content of function overloading: number of parameters, parameter type, arguments, pseudo array, typeof, constructor, difference-string and object.
Key Content of the scope: function division, global scope, global object, window object attributes, local scope, explicit declaration, and implicit declaration.
Key Content of the context object: this variable, call, apply, parameter difference, array.
The key content of the closure is: inner function, outer function, variable, setTimeout, closure problem, last assignment, closure and scope.