Closure: A function onef return to another function Innerf, and then run outside the ONEF function Innerf, if innerf is useful to the variables defined in Onef, then still can be referenced,
But the value of the variable is not the value of the variable that defines the function innerf at that time, but the value of the variable when the function Innerf is run (it is likely that the variable value differs from the value of the variable when the function Innerf is already running ONEF).
function Onef () { var arr=[]; for (var i=0;i<3;i++) { arr[i]=function() {alert (i);}; } return arr; } ONEF () [0] (); // 3 instead of 0
To change to 0, you can save the value of I by executing it immediately after defining the function:
Example 2:
function Onef () { var arr=[]; for (var i=0;i<3;i++) { arr[i]= (function(pi) { return function () {alert (pi);} }) (i); // an anonymous self-executing function is immediately returned to the function stored in ARR } return arr; } ONEF () [0] (); // 0
Use:
1: The anonymous self-executing function is the application of the closure mechanism, as in the above example Arr[i]=function () {alert (pi);}, where the PI is called the parent function of the parameter pi.
2: The variable can be kept in memory, for the value that needs to save the variable is provided for the next use, such as cumulative results or save the first calculated value, the second time can be used directly.
function Onef () { var a=0; function Innerf () {a=a+10; alert (a);} return Innerf;} var f=Onef (); F (); // tenF (); // -
Consider the following example (in conjunction with Example 2):
function Onef () { var a=0; function Innerf () {a=a+10; alert (a);} return //ten//??
Note the execution environment of the closure function:
var name= ' global name '; var obj={ name:' local name ', f:function() {return function() {alert (this. Name);}}};o BJ.F () ();
The result is ' global name ', because function () {alert (this.name)} is run in the global environment when it is actually running.
Save cache:
varobj={A:' Default ', Onef:function(){ varthat= This; return function(){ if(that.a!== ' default ') {alert (' after first run: ' +that.a);} Else{//the value of a is obtained after a series of complex operationsThat.a=8; Alert (' First run: ' +that.a); } } }};varf=Obj.onef (); F (); //First run: 8f ();//after first run: 8
About JS closed-Bag Miscellaneous