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
方法。
此規則的不正確程式碼範例
在遊樂場中開啟
/*eslint no-prototype-builtins: "error"*/
var hasBarProperty = foo.("bar");
var isPrototypeOfBar = foo.(bar);
var barIsEnumerable = foo.("bar");
此規則的正確程式碼範例
在遊樂場中開啟
/*eslint no-prototype-builtins: "error"*/
var hasBarProperty = Object.prototype.hasOwnProperty.call(foo, "bar");
var isPrototypeOfBar = Object.prototype.isPrototypeOf.call(foo, bar);
var barIsEnumerable = {}.propertyIsEnumerable.call(foo, "bar");
何時不使用它
如果您的程式碼僅接觸具有硬編碼鍵的物件,並且您永遠不會使用遮蔽 Object.prototype
方法或不繼承自 Object.prototype
的物件,您可能會想要關閉此規則。
版本
此規則是在 ESLint v2.11.0 中引入的。