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);

已知限制

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

资源

ESLint 中文网
粤ICP备13048890号