Today, in addition to the code to read the next JS closure, with respect to the previous understanding has a little more depth of understanding. Share My understanding here:
This article is divided into five large parts: 1. Understand JS before the closure needs to understand the other reading. Characteristics of 2.js closures. 3. Closure examples. 4. Benefits of using JS closures. The use of 5.js closures. 6. Optimize my JS code.
1: Understand JS closure before the need to understand JS other A:JS scope chain
JS scope chain: The scope chain is the JS function defined at the time of creation, used to find an index to the variable. The internal rules of the scope chain index are to put the local variables of the function itself first, put the parent function variables in the second, and then put the variables of the higher-level function back, and so on, so that the global object is known. When you need to find a variable, the JS interpreter will look for the variable from the scope chain, start with the local variable of the function, or, if not, find it at the next-level scope chain, return the variable if it finds the corresponding variable, or return undefined if the corresponding variable is not found until the end.
B:JS Memory Recovery mechanism
JS Memory recovery mechanism: a function at the beginning of the execution, will be defined in the variable memory space to save, in case of the subsequent statements to use, wait until the function is finished to return, these variables are considered useless, the corresponding space is recycled. The next time the function is executed, all the variables return to their original state and are re-assigned to use. But if another function is nested inside the function (which is the closure), the function is potentially called externally. And this internal function uses some variables of the external function. This memory-recycling mechanism can cause problems. If an intrinsic function is called directly after the external function is returned, the intrinsic function cannot read the value of the variable in the external function that he needs. So the JS interpreter will automatically save the function and the variables he might use, including the local variables and the variables (free variables) of the parent and ancestor functions, when it encounters the function definition. That is, building a closure, these variables will not be recycled by the memory collector, only if the internal function is not possible to be called later (for example, deleted, or without a pointer), the closure will be destroyed, and no one of the closure reference of the variable will be the next time the memory collection is started by the recycle.
Characteristics of 2:JS closures
A: The outer layer of the closure is a function, and there is a function inside the closure.
B: The closure will return the inner function, and the function returned by the closure cannot have a return inside. (If there is an end closure)
C: After the closure is executed, the internal variables of the closure are present, and the internal variables of the inner functions of the closures are recycled.
3:js Closure Example
1 function Outerfun () { 2 var myval=0; 3 function Innerfun () { 4 alert (++myval); 5 6 return Innerfun; 7 8 var myfun = Outerfun (); 9 myfun (); Myfun ();
This JS code in the process of execution, respectively, alert 1, 2. It can be concluded that the internal variables of the closure are present after the closure, and the internal variables of the inner functions of the closures are recycled.
4: Benefits of using JS closures
Using closures has the following advantages:
A: I want a variable to be stationed in memory for a long time.
B: Avoid the pollution of global variables.
var abc = (function() { ///ABC is the return value of the external anonymous function var a = 1; return function () { a+ +; alert (a); }}) (); ABC (); // 2; Call an ABC function, which is actually the return value of the internal function inside the call ABC (); // 3
C: The existence of a private member.
var AAA = (function () { var a = 1; function BBB () {A ++; alert (a); function CCC () {a ++; alert (a); return {b:bbb, // C:CCC}}); aaa.b (); // 2 aaa.c () // 3
Use of 5:JS closures
A: Anonymous self-executing function.
(function() { alert ("entered on Execution");}) ();
We create an anonymous function and execute it immediately, because the external cannot reference its internal variables, so it will be released soon after execution, the key is that this mechanism does not pollute the global object.
B: Use closures to cache data.
When we do projects, we often encounter data that is very large and does not need to be queried in a timely manner. Drop box data as follows. So at this point we can start the application in the page to cache the data, if the cache has the data we need to read the cache directly, if the cache does not have the data we need to query the database. Closures can do this for us.
varCachedsearchdata = (function () { varCacheData = [], Count =cachedata.length; return{getsearchdata:function(ID) {if(IDinchCacheData) {//If the result is in the cache returnCachedata[id];//directly returns objects in the cache}Else { //Find in a databaseAlert ("Search in Database"); }}, Clearsearchdata:function(ID) {if(Dsidinchcache) {cache[dsid].clearselection (); } } }; })(); Cachedsearchdata.getsearchdata (77);
6: Optimize my JS code
You can use closures to optimize some code in future JS code.
varperson =function(){ //variable scope is inside function, external unreachable varName = "Default"; return{getName:function(){ returnname; }, SetName:function(newName) {name=NewName; } } }(); alert (person.name);//direct access with a result of undefinedalert (Person.getname ()); Person.setname ("Zhangsan"); Alert (Person.getname ());
JS Closure detailed