no-extend-native

禁止扩展原生类型

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

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

// 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 循环的内部。但是,如果在整个代码库中严格执行此规则,则无需采取该步骤。

规则详情

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

P6820Z8G9wSG50SW7a53cABVQLzOImcIRV+hQUkxjXCO67pG2wyQwHch0OYzHhMo

/*eslint no-extend-native: "error"*/

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

选项

LDSrNtOr/P9+HeB4bDtfEnLFwaso5lCsRFlvN04zcXTx5+zDTqXIA5c3o8ViKWEtag8LjcOFnRHeNlCMsXqhYUQGRxSdHjRmPhLmeJodwNnaVzk9p3qWNRFOtIokVIEp

exceptions

kCWQAILfLXiNSqYJMMPhUj2xiO18VUk+ibzwusSP6d8eUPbhgL2X0y5wgKsgIjsKsOoaXESQ6AjN16f6igo/t6iXAm3HxSxP1xao7a0xNMA=

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

Object.prototype.a = "a";

已知限制

9p6vb9HRkb+pp3vNy+KCVY73b0G3m/I9ETZJImI0mnAM7yXC9wNNuolyUlRsz0ZQR0MeK7+JxlHWmwgdBcWAjeFhVCrFNkpdO9brcwGyDzY8w+jXVDZEoQbo3sS1DJwb

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

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

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

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

何时不使用

oMpDQwTm1UAm/V0WD93FSAkmmjh0fq/WgdNUzMmBx0KJpegA6o0bKZ+U2h1Th3UGmy51hcVplTESJpJ3bht12gg5bCEnXCZ3lFlhTCx6xT3KygElnabdcRRSyxBU44sglrk4EbadQ/B+8Aa0Dwvt2S0YlzAZwyJqnSB8BKXg+80at213tDNfPYVCXM2hhfoXmGQP5dDYYHv41zpJs+UtlFJ+pf9E55NlgsUL+oBziE+sDM058cFEpNL6qxcAFR3d69mAUBZk1YOjSDAA6bivNd8mbSFfug8P+vEuLifK2kI5ObLAI6LY0DhxTHyR6sXOSYByK33vEVmGuv/mjMXICw==