1. What are closures?
A closure is a function that accesses a variable in another function and is called a closure. function a(propName){ return function(){ return propName}}
2. What causes closures?
Closures are related to scope chains. Code will form a scope chain when executed. Function A has closure B, and the closure B’s scope chain will hold variables referenced by function A. The scope of a closure includes the scope of the closure itself, the scope of external functions, and the scope of the global environment
3. Closure disadvantages
Closure disadvantage 1: Referencing variables can hog memory and affect program quality. Closure disadvantage 2: The object variable referenced by the closure is the last value of that variable, so the variable is not necessarily in its current state.
function createFunctions() {
var result = new Array(a);for (var i = 0; i < 10; i++) {
result[i] = function () {
return i;
};
}
return result;
}
Copy the code
They both refer to the same variable I, so they both return 10
4. Closures and this
This is usually the execution environment of a function, and in closures this is usually the global environment.
var name = "The Window";
var object = { name: "My Object".getNameFunc: function () {
return function () { return this.name; }; }}; alert(object.getNameFunc()());//"The Window"
Copy the code
Reason: Each function can only access its own this and arguments, and this in a closure cannot be searched for in an external function.