no-useless-call
禁止不必要的 .call()
和 .apply()
呼叫
函數調用可以使用 Function.prototype.call()
和 Function.prototype.apply()
撰寫。但是 Function.prototype.call()
和 Function.prototype.apply()
比正常的函數調用慢。
規則詳情
此規則旨在標記可以使用正常函數調用替換的 Function.prototype.call()
和 Function.prototype.apply()
的用法。
此規則的錯誤程式碼範例
在遊樂場開啟
/*eslint no-useless-call: "error"*/
// These are same as `foo(1, 2, 3);`
;
;
;
;
// These are same as `obj.foo(1, 2, 3);`
;
;
此規則的正確程式碼範例
在遊樂場開啟
/*eslint no-useless-call: "error"*/
// The `this` binding is different.
foo.call(obj, 1, 2, 3);
foo.apply(obj, [1, 2, 3]);
obj.foo.call(null, 1, 2, 3);
obj.foo.apply(null, [1, 2, 3]);
obj.foo.call(otherObj, 1, 2, 3);
obj.foo.apply(otherObj, [1, 2, 3]);
// The argument list is variadic.
// Those are warned by the `prefer-spread` rule.
foo.apply(undefined, args);
foo.apply(null, args);
obj.foo.apply(obj, args);
已知限制
此規則靜態比較程式碼,以檢查 thisArg
是否已變更。因此,如果關於 thisArg
的程式碼是動態表達式,則此規則無法正確判斷。
此規則的錯誤程式碼範例
在遊樂場開啟
/*eslint no-useless-call: "error"*/
;
此規則的正確程式碼範例
在遊樂場開啟
/*eslint no-useless-call: "error"*/
a[++i].foo.call(a[i], 1, 2, 3);
何時不應使用
如果您不想收到關於不必要的 .call()
和 .apply()
的通知,您可以安全地停用此規則。
相關規則
版本
此規則在 ESLint v1.0.0-rc-1 中引入。