我看到很多人这样做
Object.prototype.foo = 'HALLO';
var hash = {baz: 'quuz'};
for ( var v in hash ) {
// Do not print property `foo`
if ( hash.hasOwnProperty(v) ) {
console.log( v + " is a hash property" );
}
}
我的问题不是.hasOwnProperty
每次您希望将 anObject
用作哈希时都进行测试,为什么不直接在对象上设置.__proto__
to呢?null
†</p>
hash.prototype = null;
hash.__proto__ = null;
for ( var v in hash ) {
// Do not print property `foo`
console.log( v + " is a hash property" );
}
我注意到这__proto__
是非标准的。但这仍然没有回答这个问题......
var foo = Object.create(null); Object.getPrototypeOf(foo);
这不可能是一个原始问题,但我找不到任何关于更改__proto__
为null
以消除必须检查继承的缺点?这种方法有什么问题,似乎使代码更快(不必检查 的属性Object
)和更清洁?
†.prototype
如果您打算将其作为未来的孩子,还有该财产。