Object.create(null) Strips The Prototype Chain

Object.create(null) removes the prototype chain, so user-controlled keys like constructor and toString resolve to your own data instead of inherited members.

JavascriptSecurity Boundaries

Code

javascriptsnippet
16 lines
// 普通对象字面量继承 Object.prototype:constructor、toString 都在链上
const plain = {};
console.log("plain['constructor'] exists:", plain.constructor !== undefined);
console.log("plain['toString'] exists  :", plain.toString !== undefined);

// 无原型字典(prototype-free):用户可控键只能命中自有数据
const query = Object.create(null);
query['constructor'] = 'safe-override';
query['toString'] = 'also-own';
console.log("safe['constructor']:", query.constructor);
console.log("safe['toString']   :", query.toString);
console.log('missing key lookup  :', query['nope']);

// 代价:字典自身不再带内置方法,统一走 Object 静态方法
console.log('Object.keys on safe :', Object.keys(query).join(', '));
console.log('JSON roundtrip keeps own keys only:', JSON.stringify(query));

Output

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

plain['constructor'] exists: true
plain['toString'] exists  : true
safe['constructor']: safe-override
safe['toString']   : also-own
missing key lookup  : undefined
Object.keys on safe : constructor, toString
JSON roundtrip keeps own keys only: {"constructor":"safe-override","toString":"also-own"}

What the code does

Top-level bindings plain, query hold the demo state — nothing sits inside a function scope.

Using it

The demo output is labeled (plain[, safe[, Object.keys on safe :), so every printed line maps back to its originating operation.

Key statements

query['constructor'] = 'safe-override';
const query = Object.create(null);
query['toString'] = 'also-own';

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `plain`, `query`.