实现说明
for (const key in roles) 是唯一的迭代点——其余代码顺序执行一遍。
演示用的数据放在这几个模块级绑定中:roles。
使用要点
- 直接运行文件,输出会带上标签,比如
admin:、constructor:、missing:——输出的每一行都能指回产生它的那次调用。
常见问题
这个示例需要哪些包?
一个都不用。代码用到的符号都在标准库里解析。 文件的状态由几个模块级绑定持有:roles。
核心语句
const roles = Object.create(null) as Record<string, string>;
roles['constructor'] = 'not-a-function';
const owned: string[] = [];
代码示例
// 无原型查找表: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(', '));