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

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

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

ES2015之后,你可使用展开操做符来调用可变函数。app

/*eslint-env es6*/

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

规则详情

这条规则说明了在什么状况下使用展开操做符来代替Function.prototype.apply()less

例子

  • 不正确的例子
/*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);
相关文章
相关标签/搜索