版本

no-useless-call

禁止不必要的 .call().apply() 调用

函数调用可以通过 Function.prototype.call()Function.prototype.apply() 编写。但是 Function.prototype.call()Function.prototype.apply() 比正常的函数调用要慢。

规则详情

此规则旨在标记可以使用正常函数调用替换的 Function.prototype.call()Function.prototype.apply() 的用法。

此规则的错误代码示例

在 Playground 中打开
/*eslint no-useless-call: "error"*/

// These are same as `foo(1, 2, 3);`
foo.call(undefined, 1, 2, 3);
foo.apply(undefined, [1, 2, 3]);
foo.call(null, 1, 2, 3);
foo.apply(null, [1, 2, 3]);

// These are same as `obj.foo(1, 2, 3);`
obj.foo.call(obj, 1, 2, 3);
obj.foo.apply(obj, [1, 2, 3]);

此规则的正确代码示例

在 Playground 中打开
/*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 的代码是动态表达式,则此规则无法正确判断。

此规则的错误代码示例

在 Playground 中打开
/*eslint no-useless-call: "error"*/

a[i++].foo.call(a[i++], 1, 2, 3);

此规则的正确代码示例

在 Playground 中打开
/*eslint no-useless-call: "error"*/

a[++i].foo.call(a[i], 1, 2, 3);

何时不使用它

如果您不想收到关于不必要的 .call().apply() 的通知,您可以安全地禁用此规则。

版本

此规则在 ESLint v1.0.0-rc-1 中引入。

资源

更改语言