Javascript closure, javascript
Address: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work
1. Simple implementation of closures
// Example 1
Function sayHello (name ){
Var words = "hello," + name;
Var sayForAlert = function (){
Alert (words );
}
SayForAlert ();
}
// SayHello ("jack ");
/*
An Example of a Closure
Two one sentence summaries:
A closure is the local variables for a function-kept alive after the function has returned, or
A closure is a stack-frame which is not deallocated when the function returns (as if a 'stack-framework' were malloc 'ed instead of being on the stack !).
*/
Function sayHello2 (name ){
Var words = "hello," + name; // local variables;
Var sayForAlert = function (){
Alert (words );
}
Return sayForAlert;
}
Var say2 = sayHello2 ("lucy ");
Say2 ();
/*
A function reference is returned as a parameter. Here it is equivalent to returning a function's
Pointer. SayForAlert and say2 point to the same function.
An important difference between javascrip and c is that the c Pointer Points to a function, while javascript is a reference pointing to a function. (Equivalent to a Hidden Pointer ).
In many languages, like c, local variables cannot be accessed after function execution is complete.
The function stack is destroyed.
In javascript, you can declare a function. And local variables can be accessed, and
It can be returned in declared functions.
*/
Function saynumadd (){
Var num = 666;
Var showAlert = function (){
Alert (num );
// Num ++; // place 2;
}
Num ++; // place 1;
Return showAlert;
}
Var sayNumber = saynumadd ();
SayNumber (); // alert 667;
/*
Note: according to the preceding execution results, num is saved as a variable.
Function calls can be obtained again. If we place num ++; in the position of place2
The result is 666, indicating that the saynumadd () Execution Process is executed in the order of execution of the function.
In 1, declare the variable num, 2, declare the function showAlert, 3, increase the variable num by 1;
When we execute sayNumber (), we can see the result saved after 667 is added.
*/
Function setupSomeGlobals (){
Var num = 666;
// Store some references to function as global variables
GetAlertNumber = function (){
Alert (num );
}
GetIncreaseNumber = function (){
Num ++;
}
GetSetNumber = function (x ){
Num = x;
}
}
SetupSomeGlobals ();
GetIncreaseNumber ();
GetAlertNumber ();
GetSetNumber (10 );
GetAlertNumber (); // 10
SetupSomeGlobals ();
GetAlertNumber (); // 666.
/*
Onte:
As shown in the preceding example,
The three functions in setupSomeGlobals are declared to have the permission to access the variables.
If we call setupSomeGlobals () Again, the new function stack will be created. the previously created getAlertNumber, getIncreaseNumber, and getSetNumber are overwritten with a new closure. (In JavaScript, another function can be declared inside the function no matter what time period. When the function outside is called, the function will be re-created .)
*/
Function buildList (list ){
Var result = [];
For (var I = 0; I <list. length; I ++ ){
Var item = 'item' + list [I];
Result. push (function () {alert (item + ''+ list [I])});
}
Return result;
}
Function testList (){
Var fnList = buildList ([1, 2, 3, 4]);
For (var j = 0; j <fnList. length; j ++ ){
FnList [j] ();
}
}
TestList (); // alert item1 undefined;
/*
The running result indicates that the function in the function can only save local variables, but cannot save parameter variables. Therefore, we should pay attention to the scope of the variables when using the function.
*/
Function callLocalVar (){
Var sayAlertName = function () {alert (name )};
Var name = "jacy ";
Return sayAlertName;
}
CallLocalVar (); // This write will first execute callLocalVar and then execute the returned sayAlertName;
/*
Note:
The summary closure function can access the variables defined in the same domain, either before or after the closure function. The same domain can be accessed.
*/
Function checkClosure (someNum, someRef ){
Var num = someNum;
Var arr = [1, 2, 3];
Var ref = someRef;
Return function (x ){
Num + = x;
Arr. push (num );
Alert ('num: '+ num +' \ n arr: '+ arr. toString ()
+ '\ N ref. someVar' + ref. someVar );
}
}
Var obj = {someVar: 4 };
Var fn1 = checkClosure (4, obj );
Var fn2 = checkClosure (5, obj );
Fn1 (1); // num: 5; arr: 1, 2, 3, 5; ref. someVar: 4;
Fn2 (1); // num: 6; arr: 1, 2, 3, 6; ref. someVar: 4;
Obj. someVar ++;
Fn1 (2); // num: 7; arr: 1, 2, 3, 5, 7; ref. someVar: 5;
Fn2 (2); // num: 8; arr: 1, 2, 3, 6, 8; ref. someVar: 5;
/*
Note:
The syntax here solves the problem that parameter variables cannot be saved. You only need to create a local scope variable to receive the value of this parameter variable.
It indicates different scopes and does not affect each other.
*/
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.