闭包存储的是其外部变量的引用而不是值。bash
function warpElements(a) {
var result = [],
i, n;
for (i = 0, n = a.length; i < n; i++) {
// console.log(i);
result[i] = function() {
// console.log(i);
return a[i];
}
// console.log(`result[${i}]:${result[i]}`);
}
// console.log(result);
return result;
}
var warpped = warpElements([10, 20, 30, 40, 50]);
var f = warpped[0];
f(); // undefined
复制代码
经过当即调用的函数表达式来建立一个局部做用域。闭包
function warpElements(a) {
var result = [],
i, n;
for (i = 0, n = a.length; i < n; i++) {
(function(j) {
result[i] = function() {
return a[j];
}
})(i)
}
return result;
}
var warpped = warpElements([10, 20, 30, 40, 50]);
var f = warpped[0];
f();
复制代码