no-prototype-builtins
禁止直接在物件上呼叫某些 Object.prototype
方法
在 ECMAScript 5.1 中,新增了 Object.create
,它能夠建立具有指定 [[Prototype]]
的物件。Object.create(null)
是一種常用模式,用於建立將用作 Map 的物件。當假設物件將具有來自 Object.prototype
的屬性時,可能會導致錯誤。此規則禁止直接從物件呼叫某些 Object.prototype
方法。
此外,物件可能具有遮蔽 Object.prototype
上內建方法的屬性,可能導致非預期的行為或阻斷服務安全性漏洞。例如,對於 Web 伺服器來說,解析來自用戶端的 JSON 輸入並直接在結果物件上呼叫 hasOwnProperty
是不安全的,因為惡意用戶端可能會傳送類似 {"hasOwnProperty": 1}
的 JSON 值,並導致伺服器崩潰。
為了避免像這樣細微的錯誤,最好始終從 Object.prototype
呼叫這些方法。例如,foo.hasOwnProperty("bar")
應替換為 Object.prototype.hasOwnProperty.call(foo, "bar")
。
規則詳情
此規則禁止直接在物件實例上呼叫某些 Object.prototype
方法。
此規則的錯誤程式碼範例
在 Playground 中開啟
/*eslint no-prototype-builtins: "error"*/
const hasBarProperty = foo.("bar");
const isPrototypeOfBar = foo.(bar);
const barIsEnumerable = foo.("bar");
此規則的正確程式碼範例
在 Playground 中開啟
/*eslint no-prototype-builtins: "error"*/
const hasBarProperty = Object.prototype.hasOwnProperty.call(foo, "bar");
const isPrototypeOfBar = Object.prototype.isPrototypeOf.call(foo, bar);
const barIsEnumerable = {}.propertyIsEnumerable.call(foo, "bar");
何時不該使用
如果您的程式碼僅處理具有硬編碼鍵的物件,並且您永遠不會使用遮蔽 Object.prototype
方法或不繼承自 Object.prototype
的物件,則您可能想要關閉此規則。
版本
此規則在 ESLint v2.11.0 中引入。