版本

prefer-spread

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

❄️ 已凍結

此規則目前為凍結狀態,不接受功能請求。

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

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

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

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

規則詳細資訊

此規則旨在標記在可以使用展開語法的情況下使用 Function.prototype.apply() 的情況。

範例

此規則的不正確程式碼範例

在 Playground 中開啟
/*eslint prefer-spread: "error"*/

foo.apply(undefined, args);
foo.apply(null, args);
obj.foo.apply(obj, args);

此規則的正確程式碼範例

在 Playground 中開啟
/*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 中引入。

資源

變更語言