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

1

15

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?

Raffo answered 30/7, 2021 at 16:12 Comment(5)
Does this answer your question? How do I access the Object.prototype method in the following logic?Ptolemaeus
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 docsRaffo
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 :DPtolemaeus
Sounds reasonable, thank you :)Raffo
This answer explains why: https://mcmap.net/q/100204/-object-hasownproperty-yields-the-eslint-39-no-prototype-builtins-39-error-how-to-fixStrikebound
A
6

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

Aristaeus answered 6/2, 2023 at 4:28 Comment(1)
hasOwn doesn't exist on type ...Neutrino

© 2022 - 2024 — McMap. All rights reserved.