【问题标题】:Practical differences of Object.hasOwnProperty vs Object.prototype.hasOwnPropertyObject.hasOwnProperty 与 Object.prototype.hasOwnProperty 的实际区别
【发布时间】:2023-04-09 15:19:01
【问题描述】:

向版主澄清 由于一些版主在扫描问题时有点快,我必须强调我不是在问为什么使用Object.prototype.hasOwnProperty.call 而不是myObject.hasOwnProperty。魔鬼在细节中。

ESLint rule no-prototype-builtins 禁止使用来自Object 原型的内置函数。它可以为您提供对抗这样的代码:

function serverMethodToParseClientInput(json){
  const o = JSON.parse(json);
  if (o.hasOwnProperty("foo")) {
    doSomethingMeaningful();
  }
}


const stringFromClient = "{\"hasOwnProperty\":1, \"reason\": \"Crash your system\"}";

serverMethodToParseClientInput(stringFromClient);

尝试在使用null 创建的对象上调用该方法,因为它们的原型也会失败,我认为这是一个更合理的防范措施。示例:const o = Object.create(null);

您应该使用Object.prototype.hasOwnProperty.call(obj, field),而不是obj.hasOwnProperty(field)。我真的看不出这和Object.hasOwnProperty.call(obj, field) 之间的区别。诚然,Object 不是它自己的原型,因此存在某种差异,但由于您可以覆盖任一对象上的道具,因此这里并没有太多保护措施,恕我直言。

所以我想知道在Object 可行的情况下达到Object 的原型是否有任何意义?

【问题讨论】:

  • Object.hasOwnProperty 真的很奇怪——你指的是Object.protoype 上的hasOwnPrototype 方法,它只是碰巧起作用,因为everything 继承自Object.prototype ,包括构造函数。你仍然可以使用它,假设没有分配给Object.hasOwnProperty,但这很混乱
  • @adiga 这不是重复的。您的链接问题只是给出了我在问题中已有的相同答案。请重读。我不奇怪为什么要在原型上使用该方法。我想知道为什么我不能只使用Object.hasOwnProperty
  • 使用Object.hasOwnProperty 使它看起来像assign 这样的静态方法。这可能会令人困惑。它将起作用,因为Object.hasOwnProperty === Object.prototype.hasOwnProperty。它类似于使用({}).hasOwnProperty.call
  • 好的,这两个 cmets 对我来说都是足够的答案(请随意实际发布答案)。所以它基本上是关于编码风格的;尽量避免混淆/模棱两可的结构。
  • 请注意,它会先查看Function.prototype 对象内部,然后再返回Object.prototype。如果您覆盖Function.prototype.hasOwnProperty = () => 'custom',它将采用该实现

标签: javascript


【解决方案1】:

使用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

【讨论】:

  • 看,这正是我在思考的问题。 Function 参考是一个很好的了解。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-31
  • 1970-01-01
  • 2016-02-10
  • 1970-01-01
  • 2013-10-18
相关资源
最近更新 更多