no-prototype-builtins

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

Recommended

配置文件 中使用来自 @eslint/jsrecommended 配置可以启用此规则

💡 hasSuggestions

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

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

¥In ECMAScript 5.1, Object.create was added, which enables the creation of objects with a specified [[Prototype]]. Object.create(null) is a common pattern used to create objects that will be used as a Map. This can lead to errors when it is assumed that objects will have properties from Object.prototype. This rule prevents calling some Object.prototype methods directly from an object.

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

¥Additionally, objects can have properties that shadow the builtins on Object.prototype, potentially causing unintended behavior or denial-of-service security vulnerabilities. For example, it would be unsafe for a webserver to parse JSON input from a client and call hasOwnProperty directly on the resulting object, because a malicious client could send a JSON value like {"hasOwnProperty": 1} and cause the server to crash.

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

¥To avoid subtle bugs like this, it’s better to always call these methods from Object.prototype. For example, foo.hasOwnProperty("bar") should be replaced with Object.prototype.hasOwnProperty.call(foo, "bar").

规则详情

¥Rule Details

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

¥This rule disallows calling some Object.prototype methods directly on object instances.

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint no-prototype-builtins: "error"*/

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

var isPrototypeOfBar = foo.isPrototypeOf(bar);

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

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint no-prototype-builtins: "error"*/

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

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

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

何时不使用

¥When Not To Use It

如果你的代码仅使用硬编码键接触对象,你可能希望关闭此规则,并且你永远不会使用隐藏 Object.prototype 方法或不继承自 Object.prototype 的对象。

¥You may want to turn this rule off if your code only touches objects with hardcoded keys, and you will never use an object that shadows an Object.prototype method or which does not inherit from Object.prototype.

版本

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

资源

ESLint 中文网
粤ICP备13048890号