版本

no-prototype-builtins

禁止直接在对象上调用某些 Object.prototype 方法

推荐

配置文件 中使用 @eslint/jsrecommended 配置启用此规则

💡 有建议

此规则报告的一些问题可以通过编辑器 建议 手动修复

在 ECMAScript 5.1 中,添加了 Object.create,它允许创建具有指定 [[Prototype]] 的对象。Object.create(null) 是一种常用模式,用于创建将用作 Map 的对象。当假设对象将具有来自 Object.prototype 的属性时,这可能会导致错误。此规则禁止直接从对象调用某些 Object.prototype 方法。

此外,对象可以具有遮蔽 Object.prototype 上内置属性的属性,这可能会导致意外行为或拒绝服务安全漏洞。例如,Web 服务器解析来自客户端的 JSON 输入并直接在结果对象上调用 hasOwnProperty 是不安全的,因为恶意客户端可能会发送类似 {"hasOwnProperty": 1} 的 JSON 值并导致服务器崩溃。

为了避免像这样的细微错误,最好始终从 Object.prototype 调用这些方法。例如,foo.hasOwnProperty("bar") 应该替换为 Object.prototype.hasOwnProperty.call(foo, "bar")

规则详情

此规则禁止直接在对象实例上调用某些 Object.prototype 方法。

此规则的 错误 代码示例

在 Playground 中打开
/*eslint no-prototype-builtins: "error"*/

const hasBarProperty = foo.hasOwnProperty("bar");

const isPrototypeOfBar = foo.isPrototypeOf(bar);

const barIsEnumerable = foo.propertyIsEnumerable("bar");

此规则的 正确 代码示例

在 Playground 中打开
/*eslint no-prototype-builtins: "error"*/

const hasBarProperty = Object.prototype.hasOwnProperty.call(foo, "bar");

const isPrototypeOfBar = Object.prototype.isPrototypeOf.call(foo, bar);

const barIsEnumerable = {}.propertyIsEnumerable.call(foo, "bar");

何时不使用

如果您代码仅处理具有硬编码键的对象,并且您永远不会使用遮蔽 Object.prototype 方法或不从 Object.prototype 继承的对象,则可以关闭此规则。

版本

此规则在 ESLint v2.11.0 中引入。

资源

更改语言