ECMAScript 2015 临时死区
ECMAScript 2015 Temporal Dead Zone
我是 ECMAScript 2015(ES6) 的新手,我正在阅读 ES6 中的临时死区:
if(typeof x === "undefined") {
console.log("x doesn't exist or is undefined");
} else {
// safe to refer to x....
}
let x = 5; //script.js:1 Uncaught ReferenceError: x is not defined
显然在 ES6 中,如果你在声明它之前使用 typeof 测试一个变量,它会抛出错误
console.log(typeof x);
let x = 5; //script.js:1 Uncaught ReferenceError: x is not defined
为什么会这样?这是一个错误吗?
事情是这样的:
Temporal dead zone and errors with let
In ECMAScript 2015, let
will hoist the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.
我是 ECMAScript 2015(ES6) 的新手,我正在阅读 ES6 中的临时死区:
if(typeof x === "undefined") {
console.log("x doesn't exist or is undefined");
} else {
// safe to refer to x....
}
let x = 5; //script.js:1 Uncaught ReferenceError: x is not defined
显然在 ES6 中,如果你在声明它之前使用 typeof 测试一个变量,它会抛出错误
console.log(typeof x);
let x = 5; //script.js:1 Uncaught ReferenceError: x is not defined
为什么会这样?这是一个错误吗?
事情是这样的:
Temporal dead zone and errors with let
In ECMAScript 2015,
let
will hoist the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.