Object.hasOwn() 与 Object.prototype.hasOwnProperty()

Ran*_*ner 29 javascript prototypal-inheritance javascript-objects hasownproperty

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

Ran*_*ner 51

用作Object.hasOwn()替代品Object.hasOwnProperty()

Object.hasOwn()旨在替代 Safari,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
Run Code Online (Sandbox Code Playgroud)

因此,在查看了Object.hasOwn()和 的Object.hasOwnProperty()实际情况后,它们似乎完全相同。那么我们为什么要使用Object.hasOwn()over 呢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
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

更多信息Object.hasOwn可以在这里找到:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn

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

  • 很好的答案。只需为想要查看更多详细信息的人(比如我)添加[原始提案](https://github.com/tc39/proposal-accessible-object-hasownproperty) 的链接即可。 (2认同)