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.

TypescriptSecurity Boundaries

Code

typescriptsnippet
16 lines
// 无原型查找表: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, constructor

What 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

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`.