如果对象可以包含自己的名为“hasOwnProperty”的属性:
> a={abc: 123};
{ abc: 123 }
> a.hasOwnProperty("abc");
true
> a['hasOwnProperty'] = 1;
1
> a.hasOwnProperty("abc");
TypeError: a.hasOwnProperty is not a function
...
这有效,有点丑陋的界面,如果你考虑 Object.keys(), Object.assign() 等..那么,有更好的方法吗?
> Object.hasOwnProperty.call(a, "abc");
true
> Object.hasOwnProperty.call(a, "hasOwnProperty");
true
为什么解决方案不应该是唯一推荐的方法?直接从对象使用方法似乎是失败的秘诀,特别是如果它包含外部数据(不受控制)
最佳答案
使用 hasOwnProperty 的适当/推荐方法是作为过滤器,或确定对象是否...具有该属性的方法。正是他们在第二个命令中使用它的方式 a.hasOwnProperty('abc')
.
通过覆盖对象 hasOwnProperty
与 a['hasOwnProperty'] = 1
的属性(property),虽然它安全有效,但只是删除了在该对象上使用 hasOwnProperty 函数的能力。
我在这里错过了你真正的问题吗?似乎您已经从示例中知道了这一点。
经过
'using methods directly from an object seems like a recipe for a failure
你指的是这样的事情:
> dog = {speak: function() {console.log('ruff! ruff!')}};
> dog.speak(); // ruff! ruff!
因为这在您可以想象的许多方面都非常有用。
关于javascript - 使用 hasOwnProperty 的合适/推荐方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41604063/