【问题标题】:What's the difference between obj.hasOwnProperty() & Object.prototype.hasOwnProperty.call()?obj.hasOwnProperty() 和 Object.prototype.hasOwnProperty.call() 有什么区别?
【发布时间】:2020-09-22 22:56:14
【问题描述】:

代码一:

obj.hasOwnProperty(prop);

代码二:

const hasOwnProperty = Object.prototype;
hasOwnProperty.call(obj, prop); 

我一直使用第一种编码风格,但在一些JS书籍或github项目中我多次看到关于第二种编码风格。 我想知道这只是一种习惯,或者真的是一种更好的方式来编写我的 js 代码。 谢谢。

【问题讨论】:

  • 你应该使用函数变量,例如当你需要根据某些条件选择函数时
  • 来自你的问题 :: 但我在一些 JS 书籍或 github 项目中多次看到第二种编码风格 ---> 是的,如果你使用 ESLint,那么它会抛出obj.hasOwnProperty() 上的一个错误,所以你需要使用另一个可能是开发人员可能选择第二种方法的原因之一,是的,它出错的原因由接受的答案或这里解释:: stackoverflow.com/q/39282873/7237613

标签: javascript


【解决方案1】:

如果obj没有被篡改,则差别相对较小。但是,如果您依赖包含原型功能的obj,那么各种东西都会妨碍您,因为您希望它能够正常工作(甚至可能是偶然的)。这就是为什么您会经常看到库直接调用原型方法,而不是依赖它们与各个对象保持联系。

考虑这种情况:

const prop = 'test';

obj = {test: 'example'};
console.log({
 'version': 'no tampering!',
 'obj.hasOwnProperty': obj.hasOwnProperty(prop),
 'Object.prototype.hasOwnProperty': Object.prototype.hasOwnProperty.call(obj, prop)
});

// someone does something you don't expect with obj
obj.hasOwnProperty = () => false;
// NOTE: This at least is a function, there is nothing to stop me from setting it to something that would BREAK the function call...
// E.g. obj.hasOwnProperty = 42;

console.log({
 'version': 'some tampering!',
 'obj.hasOwnProperty': obj.hasOwnProperty(prop),
 'Object.prototype.hasOwnProperty': Object.prototype.hasOwnProperty.call(obj, prop)
});

或者,如果obj 是一个不继承Object 原型的对象呢?

const obj =  Object.create(null);

console.log(obj.hasOwnProperty);

【讨论】:

  • 谢谢。我认为这种风格确实有助于避免对类型的一些判断,但我从未考虑过有人会尝试更改属性 ``` hasOwnProperty``` 甚至从 null 中继承.. 明白了
猜你喜欢
  • 2017-09-02
  • 2010-10-02
  • 2011-12-12
  • 2010-09-16
  • 2012-03-14
  • 2012-02-06
  • 2011-02-25
  • 2011-11-22
  • 2015-03-26
相关资源
最近更新 更多