Object.hasOwn()方法
Object.hasOwn()
方法是ES2022
新提出的,用于替代Object.prototype.hasOwnProperty()
的方法。根据MDN文档中的介绍:如果指定的对象具有作为其自身属性的指定属性,则hasOwn()
方法返回true
;如果该属性是继承的或不存在,则该方法返回false
。
let obj = {name: 'aa'};
console.log(Object.hasOwn(obj, 'name')); // true
console.log(Object.hasOwn(obj, 'age'));// false
Object.hasOwn()
与Object.hasOwnPeoperty()
的区别:因为实例的hasOwnProperty
方法是从Object
的原型上拿到的,如果使用Object.create(null)
的方式创建一个对象那么就拿不到hasOwnProperty
这个方法,而hasOwn
作为Object
的静态方法是可以直接通过Object
来进行调用。
如下:
const obj1 = Object.create(null);
obj1.name = '111';
console.log(obj1.hasOwnProperty('name')); // 报错
const obj2 = Object.create(null);
obj2.name = '222';
console.log(Object.hasOwn(obj2, 'name')); // true
const obj3 = {
p: 1,
hasOwnProperty: function () {
return false
}
}
console.log(Object.hasOwn(obj3, 'p')); // true