跳至內容

eslint/no-extend-native 可疑

作用

防止使用新的屬性擴展原生全域物件,例如 ObjectStringArray

為什麼這樣不好?

擴展原生物件可能會導致意外的行為,並與其他程式碼產生衝突。

例如

js
// Adding a new property, which might seem okay
Object.prototype.extra = 55;

// Defining a user object
const users = {
  1: "user1",
  2: "user2",
};

for (const id in users) {
  // This will print "extra" as well as "1" and "2":
  console.log(id);
}

範例

此規則的不正確程式碼範例

js
Object.prototype.p = 0;
Object.defineProperty(Array.prototype, "p", { value: 0 });

此規則的正確程式碼範例

js
x.prototype.p = 0;
Object.defineProperty(x.prototype, "p", { value: 0 });

參考

在 MIT 授權下發布。