实现说明
真正干活的是函数 probe、probeVar,其余都是接线。
使用要点
- 演示输出是带标签的(
after declaration:、reassign const ->),每个操作都会留下自己的一行标注。
常见问题
这个示例需要哪些包?
一个都不用。代码用到的符号都在标准库里解析。 文件在加载时定义 probe、probeVar。
入口签名:function probe()
核心语句
return phase; // declared below: still inside the temporal dead zone
} catch (error) {
return `${error.constructor.name}: ${error.message}`;
return `var reads ${legacy}`;
代码示例
// let/const bindings are hoisted but stay uninitialized until the
// declaration line runs — that window is the temporal dead zone, and
// any access in it throws a ReferenceError instead of reading undefined
function probe() {
try {
return phase; // declared below: still inside the temporal dead zone
} catch (error) {
return `${error.constructor.name}: ${error.message}`;
}
let phase = 'run';
}
console.log(probe());
let phase = 'done';
console.log('after declaration:', phase);
// Reassignment of const fails with TypeError — a different error class
const limit = 3;
try {
limit = 4;
} catch (error) {
console.log('reassign const ->', error.constructor.name);
}
// var has no dead zone: hoisting initializes the binding to undefined
function probeVar() {
return `var reads ${legacy}`;
var legacy = 'hoisted';
}
console.log(probeVar());