← 中文资源

简体中文版本

Object.freeze 保护共享表

Object.freeze 冻结共享的数组和对象:ESM 严格模式下改写直接抛 TypeError,默认值不会被意外覆盖,冻结状态可以用 try/catch 明确验证。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

array frozen: true
object frozen: true
modes intact: fast, safe
port intact: 8080

实现说明

顶层就这几处状态:MODES、defaults。

使用要点

  • 直接运行文件,输出会带上标签,比如 array frozen:、object frozen:、modes intact:——输出的每一行都能指回产生它的那次调用。

常见问题

不安装任何包也能运行吗?

可以,开箱即跑——没有引用任何内建 API 之外的东西。 状态都挂在模块顶层:MODES、defaults。

核心语句

const defaults = Object.freeze({ host: 'localhost', port: 8080 });
const MODES = Object.freeze(['fast', 'safe']);
defaults.port = 9090;

代码示例

// freeze 冻结对象与数组:ESM 严格模式下改写会直接抛 TypeError
const MODES = Object.freeze(['fast', 'safe']);

try {
  MODES.push('debug');
} catch (error) {
  console.log('array frozen:', error instanceof TypeError);
}

const defaults = Object.freeze({ host: 'localhost', port: 8080 });

try {
  defaults.port = 9090;
} catch (error) {
  console.log('object frozen:', error instanceof TypeError);
}

console.log('modes intact:', MODES.join(', '));
console.log('port intact:', defaults.port);