// main.js —— TDZ 与提升的最小复现 // 关键区别:未声明变量 typeof 返回 'undefined';TDZ 中的变量连 typeof 都抛错。 export function typeofUndeclared() { // 没有声明过,typeof 是安全的 return typeof neverDeclaredAnywhere; } export function typeofInTdz() { const log = []; try { log.push(typeof later); // 抛 ReferenceError:TDZ 不是「未定义」 } catch (e) { log.push(e.constructor.name); } let later = 1; return { log, later }; } export function varHoisting() { const log = []; log.push(typeof hoisted); // 'undefined':声明被提升,但初始化留在原处 var hoisted = 1; log.push(hoisted); return log; } export function letIsBlockScoped() { const log = []; { let inner = 'in'; log.push(inner); } log.push(typeof inner); // 'undefined':块外没有这个绑定 return log; } export function classInTdz() { try { new NotYet(); } catch (e) { return e.constructor.name; } class NotYet {} return '没有抛错'; } export function constMustBeInitialized() { // 这一行是语法错误,无法在运行时演示;用 eval 捕获语法阶段的影响 try { // eslint-disable-next-line no-eval eval('const x;'); return '没有抛错'; } catch (e) { return e.constructor.name; } } export function run(log = console.log) { const rows = [ ['typeof 未声明变量', typeofUndeclared()], ['typeof TDZ 中的 let', typeofInTdz().log.join(' → ')], ['var 在声明前读取', varHoisting().join(' → ')], ['let 的块级作用域', letIsBlockScoped().join(' → ')], ['new 一个 TDZ 中的 class', classInTdz()], ['const 不带初始化', constMustBeInitialized()], ]; log('场景 => 结果'); for (const [label, value] of rows) log(`${label} => ${value}`); log('-'.repeat(50)); log('要点:var 的声明提升且初始化为 undefined;let/const/class 被提升但留在 TDZ,访问即 ReferenceError。'); return rows; }