Index

prefer-object-has-own

不允许使用 Object.prototype.hasOwnProperty.call(),更喜欢使用 Object.hasOwn()

🔧 Fixable

此规则报告的一些问题可通过 --fix 命令行 选项自动修复

编写如下代码很常见:

🌐 It is very common to write code like:

if (Object.prototype.hasOwnProperty.call(object, "foo")) {
  console.log("has property foo");
}

这是一个常见的做法,因为 Object.prototype 上的方法有时可能不可用或被重新定义(参见 no-prototype-builtins 规则)。

🌐 This is a common practice because methods on Object.prototype can sometimes be unavailable or redefined (see the no-prototype-builtins rule).

在 ES2022 中引入,Object.hasOwn()Object.prototype.hasOwnProperty.call() 的一个更简短的替代方案:

🌐 Introduced in ES2022, Object.hasOwn() is a shorter alternative to Object.prototype.hasOwnProperty.call():

if (Object.hasOwn(object, "foo")) {
  console.log("has property foo")
}

规则详情

🌐 Rule Details

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

在线运行
/*eslint prefer-object-has-own: "error"*/

Object.prototype.hasOwnProperty.call(obj, "a");

Object.hasOwnProperty.call(obj, "a");

({}).hasOwnProperty.call(obj, "a");

const hasProperty = Object.prototype.hasOwnProperty.call(object, property);

符合此规则的正确代码示例:

🌐 Examples of correct code for this rule:

在线运行
/*eslint prefer-object-has-own: "error"*/

Object.hasOwn(obj, "a");

const hasProperty = Object.hasOwn(object, property);

选项

🌐 Options

此规则没有选项。

🌐 This rule has no options.

何时不使用

🌐 When Not To Use It

除非你的代码库支持 ES2022,否则不应使用此规则。

🌐 This rule should not be used unless ES2022 is supported in your codebase.

版本

此规则是在 ESLint v8.5.0 中引入。

进阶读物

资源