Object.create(null) Blocks Inherited Keys
Object.create(null) builds lookup maps without Object.prototype, so inherited names like constructor cannot shadow user keys or leak through for-in scans.
Code
// 无原型查找表: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(', '));Output
Captured from a sandboxed run of this snippet in the build pipeline.
admin: full
constructor: not-a-function
missing: undefined
own keys: admin, constructorWhat the code does
Repetition is confined to for (const key in roles) — the rest of the file is straight-line.
Module-level bindings hold the data — roles — with no function scope in between.
Using it
Look for the admin:, constructor:, missing: prefixes when the file runs; they tie each line to its step.
Key statements
const roles = Object.create(null) as Record<string, string>;
roles['constructor'] = 'not-a-function';
const owned: string[] = [];
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
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. Its state lives in module-level bindings: `roles`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.