← 中文资源

简体中文版本

Object.create(null) 隔离原型键

Object.create(null) 生成没有原型的查找表:constructor、toString 等继承键无法再遮蔽用户写入的数据,for-in 也只会枚举自有键,免掉逐键过滤。

阅读英文原文

运行结果

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

admin: full
constructor: not-a-function
missing: undefined
own keys: admin, constructor

实现说明

for (const key in roles) 是唯一的迭代点——其余代码顺序执行一遍。 演示用的数据放在这几个模块级绑定中:roles。

使用要点

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

常见问题

这个示例需要哪些包?

一个都不用。代码用到的符号都在标准库里解析。 文件的状态由几个模块级绑定持有:roles。

核心语句

const roles = Object.create(null) as Record<string, string>;
roles['constructor'] = 'not-a-function';
const owned: string[] = [];

代码示例

// 无原型查找表:constructor/toString 等键不再撞上 Object.prototype
const roles = Object.create(null) as Record<string, string>;
roles['admin'] = 'full';
roles['constructor'] = 'not-a-function';

// 普通对象上 roles['constructor'] 会沿原型链找到函数;这里拿到的是写入的值
console.log('admin:', roles['admin']);
console.log('constructor:', roles['constructor']);
console.log('missing:', roles['nope']);

// for-in 只枚举自有键,无需 hasOwnProperty 过滤
const owned: string[] = [];
for (const key in roles) {
  owned.push(key);
}
console.log('own keys:', owned.join(', '));