This section demonstrate that hasOwn()
is immune to the problems that affect hasOwnProperty
. Firstly, it can be used with objects that have reimplemented hasOwnProperty()
:
let foo = {
hasOwnProperty: function() {
return false;
},
bar: 'The dragons be out of office'
};
if (Object.hasOwn(foo, 'bar')) {
console.log(foo.bar);
}
It can also be used to test objects created using Object.create(null)
. These do not inherit from Object.prototype
, and so hasOwnProperty()
is inaccessible.
let foo = Object.create(null);
foo.prop = 'exists';
if (Object.hasOwn(foo, 'prop')) {
console.log(foo.prop);
}