使用展开操符作替代 .apply() (prefer-spread)

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

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

ES2015以后,你可以使用展开操作符来调用可变函数。

/*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"*/

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

原文地址:https://www.cnblogs.com/Phantom01/p/5892344.html