Object.hasOwn Ignores The Prototype Chain

Detect whether a caller set an option with Object.hasOwn, which ignores the prototype chain that the in operator walks and survives Object.create(null).

JavascriptData Integrity

Code

javascriptsnippet
22 lines
// 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'));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

How the snippet works

Repetition is confined to for (const key of Object.keys(options)) — the rest of the file is straight-line.

Module-level bindings hold the data — defaults, options, runtime, bare — with no function scope in between.

The top-level object literal pins verbose, timeout as plain values — no derivation, no imports behind them.

Using it

Look for the in:, hasOwn:, timeout own: prefixes when the file runs; they tie each line to its step.

Key statements

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

Interactive Tools for This Topic

FAQ

Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. Its state lives in module-level bindings: `defaults`, `options`, `runtime`.