Object.hasOwn() method
Object.hasOwn()
method is ES2022
newly proposed for alternative Object.prototype.hasOwnProperty()
methods. According to the introduction in the MDN documentation : If the specified object has the specified property as its own property, the hasOwn()
method returns true
; if the property is inherited or does not exist, the method returns false
.
let obj = {name: 'aa'};
console.log(Object.hasOwn(obj, 'name')); // true
console.log(Object.hasOwn(obj, 'age'));// false
Object.hasOwn()
The difference between and Object.hasOwnPeoperty()
: Because hasOwnProperty
the method of the instance is Object
obtained from the prototype, if you use Object.create(null)
the method to create an object, you can't get hasOwnProperty
this method, and the static method hasOwn
as Object
the method can be called directly Object
.
as follows:
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