← 中文资源

简体中文版本

Object.hasOwn 不看原型链

Object.hasOwn 只检查自有属性:in 会沿原型链命中默认值,判断用户是否显式设置过配置项必须用它;它是静态方法,在 Object.create(null) 的对象上依然可用。

阅读英文原文

运行结果

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

in: true
hasOwn: false
timeout own: true
{"verbose":false,"timeout":10}
bare own hasOwnProperty: undefined
bare Object.hasOwn: true

实现说明

在这里做循环的是 for (const key of Object.keys(options))。 各个操作都建立在顶层绑定之上:defaults、options、runtime、bare。 顶层对象字面量把 verbose、timeout 定成普通值——没有派生,背后也没有导入。

使用要点

  • 每一步打印都带着自己的标签:in:、hasOwn:、timeout own:。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 文件用顶层绑定保存自己的状态:defaults、options、runtime。

核心语句

if (Object.hasOwn(options, key)) runtime[key] = options[key];
const options = Object.create(defaults); // 原型上带着默认值
options.timeout = 10;
const defaults = { verbose: false, timeout: 30 };

代码示例

// Object.hasOwn: 只检查自有属性,不沿原型链向上找
const defaults = { verbose: false, timeout: 30 };
const options = Object.create(defaults); // 原型上带着默认值
options.timeout = 10;

// in 会沿原型链命中 verbose;判断"用户是否显式设置过"必须用 hasOwn
console.log('in:', 'verbose' in options);
console.log('hasOwn:', Object.hasOwn(options, 'verbose'));
console.log('timeout own:', Object.hasOwn(options, 'timeout'));

// 只把用户显式设置的项合并进运行配置
const runtime = { ...defaults };
for (const key of Object.keys(options)) {
  if (Object.hasOwn(options, key)) runtime[key] = options[key];
}
console.log(JSON.stringify(runtime));

// 对照:hasOwnProperty 是实例方法,Object.create(null) 之后不可用
const bare = Object.create(null);
bare.token = 'abc';
console.log('bare own hasOwnProperty:', typeof bare.hasOwnProperty);
console.log('bare Object.hasOwn:', Object.hasOwn(bare, 'token'));