no-extend-native

禁止扩展原生类型

在 JavaScript 中,你可以扩展任何对象,包括内置对象或 “native” 对象。有时人们会改变这些原生对象的行为,从而打破在代码的其他部分对它们所做的假设。

¥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
var users = {
    "123": "Stan",
    "456": "David"
};

// not what you'd expect
for (var 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:

var 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

当使用 polyfill 尝试使用最新规范修补旧版本的 JavaScript 时,你可能希望禁用此规则,例如以未来友好的方式可能会 Function.prototype.bindArray.prototype.forEach 的那些。

¥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 中引入。

资源

ESLint 中文网
粤ICP备13048890号