Index

no-extend-native

禁止扩展原生类型

在 JavaScript 中,你可以扩展任何对象,包括内置或“原生”对象。有时人们会以破坏代码其他部分对这些对象假设的方式更改这些原生对象的行为。

🌐 In JavaScript, you can extend any object, including builtin or “native” objects. Sometimes people change the behavior of these native objects in ways that break the assumptions made about them in other parts of the code.

例如,这里我们覆盖了一个内置方法,该方法将影响所有对象,甚至是其他内置方法。

🌐 For example here we are overriding a builtin method that will then affect all Objects, even other builtins.

// seems harmless
Object.prototype.extra = 55;

// loop through some userIds
const users = {
    "123": "Stan",
    "456": "David"
};

// not what you'd expect
for (const id in users) {
    console.log(id); // "123", "456", "extra"
}

一个常见的建议是用 users.hasOwnProperty(id) 封装 for 循环的内部以避免这个问题。然而,如果在整个代码库中严格执行这一规则,你就不需要采取这一步骤。

🌐 A common suggestion to avoid this problem would be to wrap the inside of the for loop with users.hasOwnProperty(id). However, if this rule is strictly enforced throughout your codebase you won’t need to take that step.

规则详情

🌐 Rule Details

不允许直接修改内置对象的原型。

🌐 Disallows directly modifying the prototype of builtin objects.

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

在线运行
/*eslint no-extend-native: "error"*/

Object.prototype.a = "a";
Object.defineProperty(Array.prototype, "times", { value: 999 });

选项

🌐 Options

此规则接受一个 exceptions 选项,可用于指定允许扩展的内置列表。

🌐 This rule accepts an exceptions option, which can be used to specify a list of builtins for which extensions will be allowed.

exceptions

示例 { "exceptions": ["Object"] } 选项的正确代码示例:

🌐 Examples of correct code for the sample { "exceptions": ["Object"] } option:

在线运行
/*eslint no-extend-native: ["error", { "exceptions": ["Object"] }]*/

Object.prototype.a = "a";

已知限制

🌐 Known Limitations

这个规则不会报告以下任何不太明显的修改内置对象原型的方法:

🌐 This rule does not report any of the following less obvious approaches to modify the prototype of builtin objects:

const x = Object;
x.prototype.thing = a;

eval("Array.prototype.forEach = 'muhahaha'");

with(Array) {
    prototype.thing = 'thing';
};

window.Function.prototype.bind = 'tight';

何时不使用

🌐 When Not To Use It

在使用尝试用最新规范修补旧版本 JavaScript 的 polyfill 时,你可能想要禁用此规则,例如那些可能以面向未来的方式 Function.prototype.bindArray.prototype.forEach 的 polyfill。

🌐 You may want to disable this rule when working with polyfills that try to patch older versions of JavaScript with the latest spec, such as those that might Function.prototype.bind or Array.prototype.forEach in a future-friendly way.

版本

此规则是在 ESLint v0.1.4 中引入。

资源