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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With