function getValue(condition) {
if (condition) {
let value = "blue";
// other code
return value;
} else {
// value 不存在这里
return null;
}
// value 不存在这里
}
console.log(typeof value); // "undefined"
if (condition) {
let value = "blue";
}
TDZ只是块绑定的一个独特方面。另一个独特的方面与它们在循环内的使用有关。
block binding in loops
var funcs = [];
for (var i = 0; i < 10; i++) {
funcs.push(function() { console.log(i); });
}
funcs.forEach(function(func) {
func(); // 输出 "10" 十次。
});
在es6之前解决这个问题可以使用IIFE。
var funcs = [];
for (var i = 0; i < 10; i++) {
funcs.push((function(value) {
return function() {
console.log(value);
}
}(i)));
}
funcs.forEach(function(func) {
func(); // 0,1,2,...
});
但是es6之后,可以直接使用let。
var funcs = [];
for (let i = 0; i < 10; i++) {
funcs.push(function() {
console.log(i);
});
}
funcs.forEach(function(func) {
func(); // outputs 0, then 1, then 2, up to 9
})