机制说明
三个 typeof 探针打印运行时分裂:window 在浏览器是 object、在 Node 是 undefined,global 相反,而 globalThis 处处是 object——每个宿主都提供的唯一句柄。
内建对象都挂在这个对象上:globalThis.Math === Math 与 globalThis.JSON === JSON 都打印 true,经 globalThis 调 Math.max 结果一致。最后用 ??= 把 RUNTIME_FLAGS 存到 globalThis 并修改,任何模块无需 import 循环即可读取。
注意事项
- 不要假设 window 或 global 存在——探测或直接用 globalThis。
- ??= 只在首次运行时播种标志对象。
核心语句
globalThis.RUNTIME_FLAGS ??= { verbose: false, retries: 3 };
代码示例
// One codebase may run in a browser, a worker, or Node: never assume window or global exists
console.log('typeof window ->', typeof window); // browser 'object', Node 'undefined'
console.log('typeof global ->', typeof global); // Node 'object', browser 'undefined'
console.log('typeof globalThis ->', typeof globalThis); // 'object' everywhere
// globalThis is the only global handle present in every runtime
console.log('same Math:', globalThis.Math === Math);
console.log('same JSON:', globalThis.JSON === JSON);
// Builtins read through it too: Math, JSON, console all hang off the same object
console.log('Math.max via globalThis:', globalThis.Math.max(3, 9));
// Register runtime flags once; any module can read them without import cycles
globalThis.RUNTIME_FLAGS ??= { verbose: false, retries: 3 };
globalThis.RUNTIME_FLAGS.verbose = true;
console.log('flags:', globalThis.RUNTIME_FLAGS.verbose, globalThis.RUNTIME_FLAGS.retries);