版本

prefer-spread

要求使用展開運算符而不是 .apply()

在 ES2015 之前,必須使用 Function.prototype.apply() 來呼叫可變參數函式。

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

在 ES2015 中,可以使用展開語法來呼叫可變參數函式。

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

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

已知限制

此規則靜態分析程式碼,以檢查是否變更了 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);

何時不該使用

此規則不應在 ES3/5 環境中使用。

在 ES2015 (ES6) 或更高版本中,如果您不想收到關於 Function.prototype.apply() 呼叫的通知,您可以安全地停用此規則。

版本

此規則在 ESLint v1.0.0-rc-1 中引入。

資源

變更語言