ECMAScript 6的let
应该提供块级作用域来避免变量提升带来的问题。但是在下面的代码中,为什么函数中的i
解析为循环的最后一个值(就像使用var
一样),而不是当前迭代的值?
"use strict";
var things = {};
for (let i = 0; i < 3; i++) {
things["fun" + i] = function() {
console.log(i);
};
}
things["fun0"](); // prints 3
things["fun1"](); // prints 3
things["fun2"](); // prints 3
根据MDN的说明,在for
循环中使用let
应该会将变量绑定到循环体的作用域。当我在块内部使用临时变量时,事情按照我的预期进行。这样做的必要性是什么?"use strict";
var things = {};
for (let i = 0; i < 3; i++) {
let index = i;
things["fun" + i] = function() {
console.log(index);
};
}
things["fun0"](); // prints 0
things["fun1"](); // prints 1
things["fun2"](); // prints 2
我使用 Traceur 和 node --harmony
测试了这个脚本。
let x = 5; for (let x = 0; x < 10; x++) { let x = 3; console.log(x); }
- joeytwiddle