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