On the internet about the closure of the introduction of too many, which led to the flooding, for the novice, the online a lot of talk about the closure is what, still use the following example:
Oh, my God, we've all seen how many times, what's the use of reading it? What's the occasion to use AH?
So I read all kinds of information, I summed up a bit:
I believe you can read my article before you should read a lot about the closure of the explanation, in fact, as long as you remember, the closure is the function inside a function, inside the function to access the parent function of the variable.
The following scenarios are used:
1. Xhr.addeventlistener ("Load", functionname, false);
What if functionname needs parameters?
A function can be defined again
function functionNameFnc(a){方法一 return function() //方法二
{
// 标示 做functionName该做的事情 已经可以用参数了 }
}
xhr.addEventListener("load",functionNameFnc(a), false);
In this code, method two in method one, method two also uses the method one inside of the variable, closure!
2.
var a = [];for (var i = 0; i < 10; i++) { a[i] = function () { console.log(i); };}
a[6](); // 10
变量i在整个函数内都有效没有得到释放。所以每一次循环,新的i值都会覆盖旧值,导致最后输出的是最后一轮的i的值。
The way to solve this problem is as follows:
for (Var i=0;i<10;i++) {
a[i]= (function (i) {
return function() { console.log(i);})(i);
}
A[6] (); 6
Anonymous functions are used here to add that the biggest use of anonymous functions is to create closures (which is one of the features of the JavaScript language), the anonymous function is executed immediately, the execution is released, the closure of a flaw is that the variable has not been released, will lead to memory leaks.
These two examples should allow you to understand the use of closures ...
Examples of use of JS closures