【发布时间】:2021-10-13 19:55:32
【问题描述】:
新方法 Object.hasOwn() 返回一个布尔值,指示指定对象是否具有指示的属性作为其自己的属性,但 Object.prototype.hasOwnProperty() 也是如此,它们之间有什么区别以及使用一个比另一个有什么好处?
【问题讨论】:
标签: javascript javascript-objects prototypal-inheritance hasownproperty hasown
新方法 Object.hasOwn() 返回一个布尔值,指示指定对象是否具有指示的属性作为其自己的属性,但 Object.prototype.hasOwnProperty() 也是如此,它们之间有什么区别以及使用一个比另一个有什么好处?
【问题讨论】:
标签: javascript javascript-objects prototypal-inheritance hasownproperty hasown
使用Object.hasOwn() 代替Object.hasOwnProperty()
Object.hasOwn() 旨在替代Object.hasOwnProperty(),是一种可供使用的新方法(但尚未得到所有浏览器(如 safari)的完全支持,但很快就会支持)
Object.hasOwn() 是一个静态方法,如果指定对象具有指定属性作为其自己的属性,则返回 true。如果该属性是继承的,或者不存在,则该方法返回 false。
const person = { name: 'dan' };
console.log(Object.hasOwn(person, 'name'));// true
console.log(Object.hasOwn(person, 'age'));// false
const person2 = Object.create({gender: 'male'});
console.log(Object.hasOwn(person2, 'gender'));// false
建议在Object.hasOwnProperty() 上使用此方法,因为它也适用于使用Object.create(null) 创建的对象以及已覆盖继承的hasOwnProperty() 方法的对象。虽然可以通过在外部对象上调用Object.prototype.hasOwnProperty() 来解决这些问题,但Object.hasOwn() 克服了这些问题,因此是首选(参见下面的示例)
let person = {
hasOwnProperty: function() {
return false;
},
age: 35
};
if (Object.hasOwn(person, 'age')) {
console.log(person.age); // true - the remplementation of hasOwnProperty() did not affect the Object
}
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
【讨论】: