13

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?

drake035
  • 3,955
  • 41
  • 119
  • 229
  • 8
    Does this answer your question? [How do I access the Object.prototype method in the following logic?](https://stackoverflow.com/questions/39282873/how-do-i-access-the-object-prototype-method-in-the-following-logic) – VtoCorleone Jul 30 '21 at 23:51
  • 1
    Thanks :) Using `Object.prototype.hasOwnProperty.call(obj, prop)` did the job yes. But that doesn't explain why ESlint refuses a code copied straight from MDN docs – drake035 Aug 02 '21 at 20:09
  • ESLint can be configured in many ways and I'd be careful having the mindset that, "if it's in MDN docs, it's the only way to do it". Documentation can get stale or be opinionated. Take the info and do what's best for you and your project :D – VtoCorleone Aug 03 '21 at 13:07
  • Sounds reasonable, thank you :) – drake035 Aug 17 '21 at 22:41
  • 2
    This answer explains why: https://stackoverflow.com/a/39283005/247696 – Flimm Nov 26 '21 at 17:46

1 Answers1

0

Use hasOwn() instead:

const myObj = {
  prop1: 'val1',
  prop2: 'val2'
}

if (!myObj.hasOwn('prop3')) {

    myObj.prop3 = 'val3'

}

Object.hasOwn() is intended as for Object.prototype.hasOwnProperty() HasOwn

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83