prefer-spread
需要扩展运算符而不是 .apply()
在 ES2015 之前,必须使用 Function.prototype.apply()
来调用可变参数函数。
¥Before ES2015, one must use Function.prototype.apply()
to call variadic functions.
var args = [1, 2, 3, 4];
Math.max.apply(Math, args);
在 ES2015 中,可以使用扩展语法来调用可变参数函数。
¥In ES2015, one can use spread syntax to call variadic functions.
var args = [1, 2, 3, 4];
Math.max(...args);
规则详情
¥Rule Details
此规则旨在在可以使用扩展语法的情况下标记 Function.prototype.apply()
的使用。
¥This rule is aimed to flag usage of Function.prototype.apply()
in situations where spread syntax could be used instead.
示例
¥Examples
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint prefer-spread: "error"*/
foo.apply(undefined, args);
foo.apply(null, args);
obj.foo.apply(obj, args);
此规则的正确代码示例:
¥Examples of correct code for this rule:
/*eslint prefer-spread: "error"*/
// Using spread syntax
foo(...args);
obj.foo(...args);
// The `this` binding is different.
foo.apply(obj, args);
obj.foo.apply(null, args);
obj.foo.apply(otherObj, args);
// The argument list is not variadic.
// Those are warned by the `no-useless-call` rule.
foo.apply(undefined, [1, 2, 3]);
foo.apply(null, [1, 2, 3]);
obj.foo.apply(obj, [1, 2, 3]);
已知限制:
¥Known limitations:
此规则静态分析代码以检查 this
参数是否已更改。因此,如果 this
参数是在动态表达式中计算的,则此规则无法检测到违规。
¥This rule analyzes code statically to check whether or not the this
argument is changed. So, if the this
argument is computed in a dynamic expression, this rule cannot detect a violation.
/*eslint prefer-spread: "error"*/
// This warns.
a[i++].foo.apply(a[i++], args);
// This does not warn.
a[++i].foo.apply(a[i], args);
何时不使用
¥When Not To Use It
此规则不应在 ES3/5 环境中使用。
¥This rule should not be used in ES3/5 environments.
在 ES2015 (ES6) 或更高版本中,如果你不想收到有关 Function.prototype.apply()
调用的通知,你可以放心地禁用此规则。
¥In ES2015 (ES6) or later, if you don’t want to be notified about Function.prototype.apply()
callings, you can safely disable this rule.
相关规则
版本
此规则是在 ESLint v1.0.0-rc-1 中引入。