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.
Code
// 普通对象字面量继承 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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.