对版主的澄清
由于一些版主在扫描问题时速度有点快,我必须强调我不是在问为什么要使用 Object.prototype.hasOwnProperty.call
而不是 myObject.hasOwnProperty
.细节决定成败。
ESLint rule no-prototype-builtins
禁止使用来自 Object
原型(prototype)的内置函数。它可以为您提供防止这样的代码的方法:
function serverMethodToParseClientInput(json){
const o = JSON.parse(json);
if (o.hasOwnProperty("foo")) {
doSomethingMeaningful();
}
}
const stringFromClient = "{\"hasOwnProperty\":1, \"reason\": \"Crash your system\"}";
serverMethodToParseClientInput(stringFromClient);
尝试在使用 null
创建的对象上调用该方法作为其原型(prototype)也会失败,我认为这是一个更合理的防范措施。示例:const o = Object.create(null);
。
您应该使用 Object.prototype.hasOwnProperty.call(obj, field)
而不是 obj.hasOwnProperty(field)
。我真的看不出这和 Object.hasOwnProperty.call(obj, field)
之间的区别。诚然,Object
不是它自己的原型(prototype),因此存在种类上的差异,但由于您可以覆盖任一对象上的 props,因此恕我直言,这里并没有太多安全措施。
所以我想知道当 Object
可以时,获取 Object
的原型(prototype)是否有任何意义?
最佳答案
使用 Object.hasOwnProperty
很奇怪,因为它让您看起来像是在使用像 Object.assign()
这样的静态方法。
它仍然有效,因为如果在 Object
上找不到属性,它会回退到 Function.prototype
对象。并且,这个对象继承自 Object.prototype
。因此,如果您有一个自定义实现 Function.prototype.hasOwnProperty
,那么 Object.hasOwnProperty
将使用该实现而不是 Object.prototype.hasOwnProperty
console.log( Object.hasOwnProperty === Object.prototype.hasOwnProperty ) // true
console.log( Object.getPrototypeOf(Object) === Function.prototype ) // true
console.log( Object.getPrototypeOf(Function.prototype) === Object.prototype ) // true
Function.prototype.hasOwnProperty = _ => 'custom implementaion in Function.prototype'
const obj = { prop: 10 }
console.log(Object.hasOwnProperty.call(obj, 'prop')) // custom implementaion
console.log(Object.prototype.hasOwnProperty.call(obj, 'prop')) // true
注意:Object.prototype.hasOwnProperty.call(myObj, prop)
和myObj.hasOwnProperty(prop)
的区别在here
关于javascript - Object.hasOwnProperty 与 Object.prototype.hasOwnProperty 的实际区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58554462/