
prefer-object-has-own
禁止使用 Object.prototype.hasOwnProperty.call()
,並偏好使用 Object.hasOwn()
🔧 可修正
此規則報告的某些問題可以透過 --fix
命令列 選項自動修正
撰寫如下程式碼非常常見
if (Object.prototype.hasOwnProperty.call(object, "foo")) {
console.log("has property foo");
}
這是一種常見的做法,因為 Object.prototype
上的方法有時可能無法使用或被重新定義(請參閱 no-prototype-builtins 規則)。
在 ES2022 中引入的 Object.hasOwn()
是 Object.prototype.hasOwnProperty.call()
的較短替代方案
if (Object.hasOwn(object, "foo")) {
console.log("has property foo")
}
規則詳細資訊
此規則的不正確程式碼範例
在遊樂場開啟
/*eslint prefer-object-has-own: "error"*/
;
;
;
const hasProperty = ;
此規則的正確程式碼範例
在遊樂場開啟
/*eslint prefer-object-has-own: "error"*/
Object.hasOwn(obj, "a");
const hasProperty = Object.hasOwn(object, property);
何時不該使用
除非您的程式碼庫支援 ES2022,否則不應使用此規則。
版本
此規則在 ESLint v8.5.0 中引入。
延伸閱讀
