当用户点击“按钮 4”时,控制台会记录什么?为什么?

What gets logged to the console when the user clicks on “Button 4” and why?

考虑以下代码片段:

for (var i = 0; i < 5; i++) {
  var btn = document.createElement('button');
  btn.appendChild(document.createTextNode('Button ' + i));
  btn.addEventListener('click', function(){ console.log(i);});
  document.body.appendChild(btn);
}

好吧,无论用户单击什么按钮,数字 5 将始终记录到控制台。

这是因为,在调用 onclick 方法(对于任何按钮)时,for 循环已经完成并且变量 i 已经具有值 5.

Bonus points, you can read more about execution contexts, variable objects, activation objects, and the internal “scope” property, this contributes to the closure behavior.And you will understand the magic here.