使用展開操符做替代 .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);
相關文章
相關標籤/搜索