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 中引入。