版本

no-param-reassign

不允許重新指派函數參數

指派給宣告為函數參數的變數可能會產生誤導,並導致混淆行為,因為當不在 strict 模式時,修改函數參數也會修改 arguments 物件(請參閱下方的 何時不該使用)。通常,指派給函數參數是無意的,並且表示錯誤或程式設計師錯誤。

此規則也可以設定為在修改函數參數時失敗。參數的副作用可能會導致違反直覺的執行流程,並使錯誤難以追蹤。

規則詳細資訊

此規則旨在防止因修改或重新指派函數參數而引起的非預期行為。

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

在 Playground 中開啟
/*eslint no-param-reassign: "error"*/

var foo = function(bar) {
    bar = 13;
}

var foo = function(bar) {
    bar++;
}

var foo = function(bar) {
    for (bar in baz) {}
}

var foo = function(bar) {
    for (bar of baz) {}
}

此規則的正確程式碼範例

在 Playground 中開啟
/*eslint no-param-reassign: "error"*/

var foo = function(bar) {
    var baz = bar;
}

選項

此規則接受一個選項,即一個物件,其中包含一個布林值屬性 "props",以及陣列 "ignorePropertyModificationsFor""ignorePropertyModificationsForRegex""props" 預設為 false。如果 "props" 設定為 true,則此規則會警告不要修改參數屬性,除非它們包含在 "ignorePropertyModificationsFor""ignorePropertyModificationsForRegex" 中,後者預設為空陣列。

props

預設 { "props": false } 選項的正確程式碼範例

在 Playground 中開啟
/*eslint no-param-reassign: ["error", { "props": false }]*/

var foo = function(bar) {
    bar.prop = "value";
}

var foo = function(bar) {
    delete bar.aaa;
}

var foo = function(bar) {
    bar.aaa++;
}

var foo = function(bar) {
    for (bar.aaa in baz) {}
}

var foo = function(bar) {
    for (bar.aaa of baz) {}
}

{ "props": true } 選項的不正確程式碼範例

在 Playground 中開啟
/*eslint no-param-reassign: ["error", { "props": true }]*/

var foo = function(bar) {
    bar.prop = "value";
}

var foo = function(bar) {
    delete bar.aaa;
}

var foo = function(bar) {
    bar.aaa++;
}

var foo = function(bar) {
    for (bar.aaa in baz) {}
}

var foo = function(bar) {
    for (bar.aaa of baz) {}
}

{ "props": true } 選項搭配設定 "ignorePropertyModificationsFor"正確程式碼範例

在 Playground 中開啟
/*eslint no-param-reassign: ["error", { "props": true, "ignorePropertyModificationsFor": ["bar"] }]*/

var foo = function(bar) {
    bar.prop = "value";
}

var foo = function(bar) {
    delete bar.aaa;
}

var foo = function(bar) {
    bar.aaa++;
}

var foo = function(bar) {
    for (bar.aaa in baz) {}
}

var foo = function(bar) {
    for (bar.aaa of baz) {}
}

{ "props": true } 選項搭配設定 "ignorePropertyModificationsForRegex"正確程式碼範例

在 Playground 中開啟
/*eslint no-param-reassign: ["error", { "props": true, "ignorePropertyModificationsForRegex": ["^bar"] }]*/

var foo = function(barVar) {
    barVar.prop = "value";
}

var foo = function(barrito) {
    delete barrito.aaa;
}

var foo = function(bar_) {
    bar_.aaa++;
}

var foo = function(barBaz) {
    for (barBaz.aaa in baz) {}
}

var foo = function(barBaz) {
    for (barBaz.aaa of baz) {}
}

何時不該使用

如果您想要允許指派給函數參數,則可以安全地停用此規則。

strict 模式程式碼不會將 arguments 物件的索引與每個參數綁定同步。因此,此規則對於防止 ESM 模組或其他 strict 模式函數中的 arguments 物件變異不是必要的。

版本

此規則在 ESLint v0.18.0 中引入。

延伸閱讀

資源

變更語言