Object.prototype.hasOwnProperty.call和{} .hasOwnProperty.call之间的区别。 [英] Difference between Object.prototype.hasOwnProperty.call and {}.hasOwnProperty.call.(eslint rule guard-for-in)
问题描述
在eslint规则后卫保护中,使用<$直接在中使用c $ c>是不正确的。好的做法是
In the eslint rule guard-for-in , use for in
directly is incorrect. The good practice is
for (key in foo) {
if (Object.prototype.hasOwnProperty.call(foo, key)) {
doSomething(key);
}
if ({}.hasOwnProperty.call(foo, key)) {
doSomething(key);
}
}
我的问题是何时 Object .prototype.hasOwnProperty.call(foo,key)
和 {}。hasOwnProperty.call(foo,key)
会导致不同的结果吗?任何人都可以举一个具体的例子吗?
My question is when Object.prototype.hasOwnProperty.call(foo, key)
and {}.hasOwnProperty.call(foo, key)
will lead different result? Anyone can show a specific example?
推荐答案
它们永远不会 1 导致不同的结果,因此将两者都考虑在内正确。
They'll never1 lead to different results, which is why both of them are considered correct.
对象 {}
始终从对象原型继承而没有自己的键,因此访问 .hasOwnProperty
方法将为您提供所需的东西。并且 Object.prototype
是全局 Object
构造函数的不可写属性,因此它始终引用对象原型
The object {}
always inherits from the object prototype and has no own keys, so accessing the .hasOwnProperty
method on it will get you what you want. And Object.prototype
is a non-writable property of the global Object
constructor, so it always refers to the object prototype as well.
现在,在某些情况下,表达式不能执行您想要的操作:
Now, there are some cases where the expression does not do what you wanted it to do:
- 有人确实覆盖了全局
Object
变量 - 有人确实掩盖了
您对象中的对象
标识符,以使其不引用全局 - 有人确实覆盖了
Object.prototype.hasOwnProperty
和其他东西 - 有人确实用其他东西覆盖了
Function.prototype.call
- Someone did overwrite the global
Object
variable - Someone did shadow the
Object
identifier in your scope so that it doesn't refer to the global - Someone did overwrite
Object.prototype.hasOwnProperty
with something else - Someone did overwrite
Function.prototype.call
with something else
1:显然,前两种情况只与 Object.prototype
引用混淆,但是他们仍然很前卫,不容忽视。
1: Obviously, the first two edge cases only mess with the Object.prototype
reference, but they're still edgy enough to be ignored.
这篇关于Object.prototype.hasOwnProperty.call和{} .hasOwnProperty.call之间的区别。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!