Object.hasOwn() vs Object.prototype.hasOwnProperty()



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

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/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

最新更新