Fixing "Do not access Object.prototype method 'hasOwnProperty' from target object" error

14.4k Views Asked by At

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?

1

There are 1 best solutions below

1
Garima Saxena On

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