Index

prefer-spread

需要扩展运算符而不是 .apply()

❄️ Frozen

此规则目前已 冻结,不接受功能请求。

在 ES2015 之前,必须使用 Function.prototype.apply() 来调用可变参数函数。

🌐 Before ES2015, one must use Function.prototype.apply() to call variadic functions.

const args = [1, 2, 3, 4];
Math.max.apply(Math, args);

在 ES2015 中,可以使用扩展语法来调用可变参数函数。

🌐 In ES2015, one can use spread syntax to call variadic functions.

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

选项

🌐 Options

此规则没有选项。

🌐 This rule has no options.

已知限制

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

资源