箭头功能捕获策略,以使声明变量
我一直在阅读乔恩·斯基特(Jon Skeet)的文章 关于封闭策略,并希望与JavaScript探索情况。
arr = [];
for(let i = 0; i < 3; i++) {
arr.push(() => console.log(i));
}
arr.forEach(ele => ele());
arr = [];
let j;
for(j = 0; j < 3; j++) {
arr.push(() => console.log(j));
}
arr.forEach(ele => ele());
令人惊讶的是,第一个打印0,1,2
和第二个3,3,3
。
我还发现 that JS总是捕获变量。那为什么第一种情况呢?
I've been reading Jon Skeet's article on closure capturing strategies and want to explore what's the case with JavaScript.
arr = [];
for(let i = 0; i < 3; i++) {
arr.push(() => console.log(i));
}
arr.forEach(ele => ele());
arr = [];
let j;
for(j = 0; j < 3; j++) {
arr.push(() => console.log(j));
}
arr.forEach(ele => ele());
Surprisingly, the first prints 0,1,2
and the second 3,3,3
.
I also found that JS always captures variables. So why the first case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我已经在控制台内添加了字符串1和2。
第一个结束是1,它可以按预期工作,因为LET关键字范围范围为for循环。另一方面,第二个循环中的console.log将scoppep的k取在窗口范围中,因此当console.log运行时,k的值将设置为for循环的末端的k值, i的值仅有效,并且在第一个循环内部范围内(因此是闭合)。
I've added the strings 1 and 2 inside the console.logs so that you can better see which one is actually going first.
The first to end is 1 and it works as expected because the let keyword is scoped to the for loop. On the other hand, console.log in the second loop takes k which is scoped in the window scope, thus when console.log runs, the value of k is going to be set to that of the end of the for loop, while the value of i is only valid and scoped (thus the closure) inside the first for loop.