我知道这看起来很傻。但刚才我试着在JS中测试closure
。
var funcList = [];
for(let i = 0; i < 3; ++i) {
funcList.push(() => { console.log(i); });
}
console.log('testing for reference');
funcList.forEach(func => func());
funcList.length = 0;
for(let i = 0; i < 3; ++i) {
funcList.push(
((i) => {
return () => { console.log(i); }
})()
);
}
console.log('testing for no reference');
funcList.forEach(func => func());
&#13;
但不幸的是,我遇到了以下问题:
预期的输出应该是(至少我认为~~,很可能的事实是我错了):
testing for reference
3
3
3
testing for no reference
0
1
2
但它给了我
testing for reference
0
1
2
testing for no reference
undefined
undefined
undefined
这里发生了什么?任何人都能揭开我的光芒吗?
非常感谢您提供任何有用的建议。
更新 2018-3-24感谢@Patrick Evans现在的工作如下:
var funcList = [];
for(var i = 0; i < 3; ++i) { // using var instead of let
funcList.push(() => { console.log(i); });
}
console.log('testing for reference');
funcList.forEach(func => func());
funcList.length = 0;
for(var i = 0; i < 3; ++i) {
funcList.push(
((i) => {
return () => { console.log(i); }
})(i) // pass in the `i`
);
}
console.log('testing for no reference');
funcList.forEach(func => func());
&#13;
更新2018-03-30
真正的闭包应该是
var funcList = [];
(function () {
let i = 0;
while (i++ < 3) {
funcList.push(() => { console.log(i); });
}
})();
console.log('testing for reference');
funcList.forEach(func => func());
&#13;
答案 0 :(得分:3)
您忘记将funcList.push(
((i) => {
return () => { console.log(i); }
})(i) //Pass i's value as param
);
的值传递给期望参数的函数。由于参数没有值,因此它会记录未定义。试试这个:
Random