
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 中引入。
延伸閱讀
