我知道这看起来很傻。但是刚才我尝试在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());
但不幸的是,我遇到了如下问题:
预期的输出应该是(至少我是这么认为的~~,事实很可能是我错了):
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());
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());
最佳答案
您忘记将 i
的值传递给需要参数的函数。由于参数没有值,因此它记录未定义。试试这个:
funcList.push(
((i) => {
return () => { console.log(i); }
})(i) //Pass i's value as param
);
关于Javascript 关闭不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49461014/