Foreword
Today saw the Little Red Book brush closures, with the Nuggets again fought a few months experience, all the way to tread regular, prototype, object inheritance, he finally jammed in here.
Note:
Javascript herein by reference from high-level programming and thought no question , dead No article .
example
Of the closure, there is a very typical example:
function createFunctions() {
var result = new Array();
for (var i = 0; i < 10; i++) {
result[i] = function() {
return i;
};
}
return result;
}
let a = createFunctions();
console.log(a[0]());
This is in accordance with what we think, certainly print is zero, but the answer is the first of several print regardless of the results of this function array is 10.
Explanation
The first link posted above, there is such a wonderful answer period:
函数1作用域
for(var i = 0; i < 10; i++) { 函数1作用域
我在函数1作用域中
result[i] = function() { 函数2作用域
我在函数2作用域中
return i;
};
}
函数1作用域
console.log(i); 毫无疑问,执行到这里的时候,i是10,既然这里是10
那么在函数2作用域中访问i也是10也就不足为奇了
因为函数2作用域中没有,向上去函数1作用域中找
Thus, it can be seen, the closure has two main scopes, scopes i 2 because of the absence of natural looking only to the 1, 10 is only natural, since the closure 1 run i scoped that is, in 10.
Extended
Here are two main mentioned help us to deepen our understanding of the way:
块1作用域
for(let i = 0; i < 10; i++) { 块2作用域
我在块2作用域中
console.log(i); // 毫无疑问,这里的i从0依次增加到10
result[i] = function() { 块3作用域
我在块3作用域中
return i;
};
}
块1作用域
Why var replaced let, an array indexing function is not obtained 10 of it? We all know that let you can create block-level scope, and therefore for each cycle, is a new block-level scope, and this scope and the global scope is not the same, naturally, can print out a 1-10 .
We can create another anonymous function to force the closure of behavior in line with expectations:
function createFunctions() {
var result = new Array();
for (var i = 0; i < 10; i++) {
result[i] = (function(num) {
return function() {
return num;
};
})(i);
}
return result;
}
let a = createFunctions();
console.log(a[0]());
Here we do not have the closure assigned to the array, but defines an anonymous function, speaking immediately the results of the anonymous function assigned to the array, while the anonymous function has a parameter num, ie the value of the last to return, calling each when the anonymous function, we pass the i, so that each function has its own copy i's.
Of course, there are other ways:
function createFunctions() {
var result = new Array();
for (var i = 0; i < 10; i++) {
result[i] = (function(num) {
return i;
})();
}
return result;
}
let a = createFunctions();
console.log(a);
And more peace of mind.
Manual nugget ~