变量捕获 [duplicate] 背后的机制

The mechanic behind the variable capture [duplicate]

提问人:korsunskyroma 提问时间:10/7/2023 最后编辑:Barmarkorsunskyroma 更新时间:10/7/2023 访问量:34

问:

我正在学习 JavaScript,目前正在学习作用域和闭包。我在维基百科中偶然发现了以下关于意外变量捕获的例子:

var elements = document.getElementsByTagName('a');
// Incorrect: e is bound to the function containing the 'for' loop, not the closure of "handle"
for (var e of elements) { 
  e.onclick = function handle() { 
    alert(e.id);
  } 
}

我了解什么是变量捕获,我只是看不出它是如何在这里发生的,如果有人可以解释这里的上下文/环境发生了什么,我将不胜感激。

JavaScript 作用域 闭包

评论

0赞 Pointy 10/7/2023
这是创建变量和创建变量之间的关键区别。letvar
1赞 Barmar 10/7/2023
声明的变量的作用域是整个函数。因此,所有迭代都共享相同的变量,闭包将获得最后一个值。vare

答: 暂无答案