Object.hasOwn()与Object.prototype.hasOwnProperty()的区别

28

新的方法Object.hasOwn()返回一个布尔值,表示指定对象是否将指示的属性作为其自己的属性,但Object.prototype.hasOwnProperty()也是如此,它们之间有什么区别?使用其中一个的好处是什么?

1个回答

47

使用 Object.hasOwn() 替代 Object.hasOwnProperty()

Object.hasOwn() 是用来替代 Object.hasOwnProperty() 的新方法,可用于检查指定对象是否含有特定属性(但并不是所有浏览器都支持,如Safari还不完全支持,但很快就会支持)

Object.hasOwn() 是一个静态方法,如果指定对象具有指定属性作为自身属性,则返回 true。如果该属性是继承的或不存在,则该方法返回 false。

const person = { name: 'John' };
console.log(Object.hasOwn(person, 'name'));// true
console.log(Object.hasOwn(person, 'age'));// false

console.log(person.hasOwnProperty('name'));// true
console.log(person.hasOwnProperty('age'));// false

const person2 = Object.create({gender: 'male'});
console.log(Object.hasOwn(person2, 'gender')); // false
console.log(person.hasOwnProperty('gender')); //false
 
// gender is not an own property of person, it exist on the person2 prototype

因此,在查看了 Object.hasOwn()Object.hasOwnProperty() 的用法之后,它们似乎非常相似。那么为什么我们应该使用 Object.hasOwn() 而不是 Object.hasOwnProperty()

推荐使用这种方法而不是 Object.hasOwnProperty(),因为它也适用于使用 Object.create(null) 创建的对象和覆盖了继承的 hasOwnProperty() 方法的对象。虽然可以通过在外部对象上调用 Object.prototype.hasOwnProperty.call(<object reference>, <property name>) 来解决这些问题,但是 Object.hasOwn() 解决了这些问题,因此更受欢迎(请参见下面的示例)。

let person = {
  hasOwnProperty: function() {
    return false;
  },
  age: 35
};
 
console.log(Object.hasOwn(person, 'age')); // true
console.log(person.hasOwnProperty('age')); // false

let person = Object.create(null);
person.age = 35;
if (Object.hasOwn(person, 'age')) {
  console.log(person.age); // true - works regardless of how the object was created
}

if (person.hasOwnProperty('age')){ // throws error - person.hasOwnProperty is not a function
   console.log('hasOwnProperty' + person.age);
}

可以在这里了解更多关于 Object.hasOwn 的信息:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn

浏览器兼容性 - https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility


2
不错的回答。只是为那些(像我一样)想要查看更多细节的人添加了一个链接到原始提案 - exmaxx
1
为什么 "console.log(Object.hasOwn(person2, 'gender'))" 返回 false? 如果您检查 person2.gender,person2 确实具有该属性吗? 它没有使用麻烦的 "Object.create(null)" 创建,所以很好奇为什么它不返回 true。 - armyofda12mnkeys
因为性别是在 person2 对象的原型上创建的,而不是在其本身上创建的。 - Ran Turner
1
非常好的答案,谢谢。需要注意的是,如果您有依赖于Node的“东西”,则需要使用node16才能使用hasOwn()。例如,Postman Monitors的节点版本尚未升级到此版本,因此任何监视器测试运行都将失败,即使在本地hasOwn()也可以正常工作。(编辑:我认为这是他们的节点问题,因为我们在Newman中更新了节点以解决此问题,但我离题了...)。因此,在选择hasOwn()时需要考虑这一点。干杯。 - Kreidol

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接