Reputation: 2897
Based on hasOwnProperty()
method docs I wrote the following:
const myObj = {
prop1: 'val1',
prop2: 'val2'
}
if (!myObj.hasOwnProperty('prop3')) {
myObj.prop3 = 'val3'
}
But I'm getting this error:
Do not access Object.prototype method 'hasOwnProperty' from target object
Why does it not work if it's the same as in the docs, and how to fix it?
Upvotes: 15
Views: 16999
Reputation: 77
Use the static Object.hasOwn()
instead:
const myObj = {
prop1: 'val1',
prop2: 'val2'
}
if (!Object.hasOwn(myObj, 'prop3')) {
myObj.prop3 = 'val3'
}
console.log(Object.keys(myObj)); //returns [ 'prop1', 'prop2', 'prop3' ]
console.log(myObj.prop3); //returns val3
Object.hasOwn()
is intended as replacement for Object.prototype.hasOwnProperty()
HasOwn
Upvotes: 6