First, feel the closure of the JavaScript function
Two, closed package
1, definition: A closure is a function that can read the internal variables of other functions, because in the JavaScript language, only the child functions inside the function can read the local variables, so the closure can be simply understood as: a function defined within a function, in short, Closures act as bridges that connect functions inside and outside functions
2, Function: 1, you can read the variables inside the function, 2, you can keep the values of these variables are always stored in memory
3, note the point: 1, first because the closure will make the variables in the function are stored in memory, memory consumption is very large, so we can not abuse closures, otherwise it will affect the performance of the Web page. There may be a memory leak in IE browser. The workaround is to remove all unused local variables before exiting the function
2, the closure changes the value of the inner variable of the parent function outside the parent function. So, if you use the parent function as an object, take the closure as its public method and take the internal variable as its private property. Be careful not to change the values of the internal variables of the parent function.
Three: Practice
var name = "the window";
var object = {
Name: "My Object",
Getnamefunc:function () {
return function () {
return this.name;
};
}
};
Alert (Object.getnamefunc () ());
"The Window" pops up because this point is pointing to the browser window object
var name = "the window";
var object = {
Name: "My Object",
Getnamefunc:function () {
var = this;
return function () {
return that.name;
};
}
};
Alert (Object.getnamefunc () ());
The "My Object" pops up because this point is pointing to the current object object
JavaScript function closure (closure)