Reading notes:
1. The closure uses the motive:
1): The function of the internal variables exposed;
2): The function internal variable resides in memory.
2, closure of the use of the way:
1 Use global variables and anonymous functions within the function body
function Obj () {
var vars = [];
Addvar is a global variable in the body of the function, and the anonymous method is the closure (which references the temporary variable VARs in the obj () method)
Addvar = function (Newvar) {
vars.push (Newvar);
}
Readvars is a global variable in the body of the function, and the anonymous method is the closure (which references the temporary variable VARs in the obj () method)
Readvars = function () {
alert (VARs);
}
After the OBJ () call, the global variables Addvar and Readvars Obj () are initialized in the body of the function
.
Addvar ("1");
Addvar ("ESDSDG");
Readvars ()//Show 1,ESDSDG
addvar ("FDSAFADSF");
Readvars ();//Display 1,ESDSDG,FDSAFADSF/
*
Summary:
after global variables Addvar and readvars initialization, because Addvar and Readvars refer to closures (anonymous methods), The
anonymous method also references a temporary variable in the body of the obj () method. Therefore, OBJ () will not be released and the
temporary variable VARs will reside in memory until the global variable Addvar and Readvars are not released.
*/
2 The internal function as the return value, the internal function (closure) exposed
function newObj () {
var vars = [];
Closure Addvar, referencing the VARs
function Addvar (newvar) {
vars.push (newvar);
alert (VARs);
}
Exposes the closure function to return
Addvar
by returning a value ObjRef refers to the closure function Addvar ()
var objRef = NEWOBJ ();
ObjRef ("T1");//t1
objRef ("T2");//t1,t2/
*
Summary:
1, function exposes closure function by return value
2, Bjref references the closure function Addvar (), the closure function uses the temporary variable in the NEWOBJ () function VARs
3, Bjref () is not released when NEWOBJ is not released
* *
3, the reference relationship is 3 +, the object will not be released, or will be recycled recycling mechanism.
Good Article recommended:
Http://www.jb51.net/article/24101.htm