drake035
drake035

Reputation: 2897

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

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

Answers (1)

Garima Saxena
Garima Saxena

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

Related Questions