Index

no-useless-call

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

函数调用可以通过 Function.prototype.call()Function.prototype.apply() 来编写。但 Function.prototype.call()Function.prototype.apply() 比普通函数调用慢。

🌐 The function invocation can be written by Function.prototype.call() and Function.prototype.apply(). But Function.prototype.call() and Function.prototype.apply() are slower than the normal function invocation.

规则详情

🌐 Rule Details

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

🌐 This rule is aimed to flag usage of Function.prototype.call() and Function.prototype.apply() that can be replaced with the normal function invocation.

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

在线运行
/*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]);

符合此规则的正确代码示例:

🌐 Examples of correct code for this rule:

在线运行
/*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);

选项

🌐 Options

此规则没有选项。

🌐 This rule has no options.

已知限制

🌐 Known Limitations

此规则通过静态比较代码来检查 thisArg 是否被修改。因此,如果关于 thisArg 的代码是动态表达式,则此规则无法正确判断。

🌐 This rule compares code statically to check whether or not thisArg is changed. So if the code about thisArg is a dynamic expression, this rule cannot judge correctly.

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

在线运行
/*eslint no-useless-call: "error"*/

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

符合此规则的正确代码示例:

🌐 Examples of correct code for this rule:

在线运行
/*eslint no-useless-call: "error"*/

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

何时不使用

🌐 When Not To Use It

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

🌐 If you don’t want to be notified about unnecessary .call() and .apply(), you can safely disable this rule.

版本

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

资源