ESLint の「Do not access Object.prototype method 'hasOwnProperty' from target object」というエラーへの対処法

2023-11-21
2分で読了
更新: 2025-12-14

目次

ESLint( v8.51.0 )を走らせた時、下記のようなエラーが出ました。

Do not access Object.prototype method 'hasOwnProperty' from target object  no-prototype-builtins

no-prototype-builtins - ESLint - Pluggable JavaScript Linter

これは、オブジェクトが Object.prototype を継承していない場合や、hasOwnProperty が上書きされている場合は意図せぬ動きになるため、hasOwnProperty を直接実行しないことが推奨されるようになったからのようです。

Object.prototype を継承していない場合

例えば、以下のようにしてオブジェクトを作ると Object.prototype が継承されません。

const obj = Object.create(null);
console.log(obj.hasOwnProperty); // => undefined となる

hasOwnProperty が上書きされている場合

例えば、以下のようにしてオブジェクトを作ると hasOwnProperty が本来の動きとは違うものになります。

const obj = {
  hasOwnProperty: function(prop) {
    alert(prop);
  }
};

console.log(obj.hasOwnProperty('property'));

これを実行するとアラートがでます。

対応方法

ということで、上の ESLint のドキュメンントにも書いてありますが、以下のように書き換えればOKです。

// Before
foo.hasOwnProperty("bar")

// After
Object.prototype.hasOwnProperty.call(foo, "bar")

この記事をシェア

関連記事