In one sentence: a closure is a function that captures external bindings within the scope.
Official definition: An expression (usually a function) that has many variables and an environment bound to these variables, because these variables are also called part of the expression.
The relationship between free variables and closures: Free variables are closed to the creation of closures.
The internal logic is
Free variables: If there are other functions inside a function, then these internal functions can access the variables declared in the external function (these variables are called free variables).
Three characteristics of closures:
1. Function nested functions
2. Functions can refer to the outside inside Parameters and variables
3. Parameters and variables will not be recycled by the garbage collection mechanism
Disadvantages of closureIt is resident in memory and will Increase memory usage, improper use can easily cause memory leaks.
Benefits of closures:
1. I hope that a variable can Long-term resident in memory
2. Avoid pollution of global variables
3. Existence of private members
function fn(){ //Closure fn() | |
var a = 10; | |
function f1(){ | |
a++; | |
console.log(a); | |
} | |
return f1; | |
} | |
var f = fn(); | |
f(); | |
f(); | |
f(); |
闭包解决索引值问题:
charset="UTF-8"> | |
Memory leak problem:
IE's JS objects and DOM objects use different garbage collection mechanisms, so closures will cause memory leaks in IE, that is, elements residing in memory cannot be destroyed. .
function closure(){ | |
##var oDiv = document.getElementById("div1");//oDiv will remain in memory after use | |
##oDiv.onclic = function(){ | |
alert("oDiv.innerHTML");//Using oDiv here will cause memory leaks | |
}; | |
##} | closure(); //Dereference oDiv to avoid memory leaks function closure(){ var oDiv = document.getElementById ("div1");//oDiv will remain in memory after use var test = oDiv.innerHTM oDiv.onclic = function(){ alert(test);//Using oDiv here will cause memory leaks }; oDiv = null ; } |
The above is the detailed content of In one sentence: What is closure?. For more information, please follow other related articles on the PHP Chinese website!