prefer-spread
在--fix
命令行上的选项可以自动修复一些被这条规则反映的问题。
在 ES2015之前,必须使用Function.prototype.apply()
调用可变参数函数。
var args = [1, 2, 3, 4];
Math.max.apply(Math, args);
在 ES2015中,可以使用 spread 运算符来调用可变参数函数。
/*eslint-env es6*/
var args = [1, 2, 3, 4];
Math.max(...args);
规则细节
该规则旨在标示Function.prototype.apply()
在可以使用分布式运算符的情况下的使用情况。
示例
此规则的错误代码示例:
/*eslint prefer-spread: "error"*/
foo.apply(undefined, args);
foo.apply(null, args);
obj.foo.apply(obj, args);
此规则的正确代码示例:
/*eslint prefer-spread: "error"*/
// Using the spread operator
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]);
已知限制:
此规则静态分析代码以检查this
参数是否已更改。因此,如果this
参数是在动态表达式中计算的,则此规则无法检测到违规行为。
/*eslint prefer-spread: "error"*/
// This warns.
a[i++].foo.apply(a[i++], args);
// This does not warn.
a[++i].foo.apply(a[i], args);
何时不使用它
此规则不应用于 ES3 / 5环境。
在 ES2015(ES6)或更高版本中,如果您不想收到有关Function.prototype.apply()
调用的通知,可以安全地禁用此规则。
相关规则
- no-useless-call
- VersionThis rule was introduced in ESLint 1.0.0-rc-1.
- 资源
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com