SyntaxError: getter functions must have no arguments

當宣告的 getter 函式引數列表不為空時,會發生 JavaScript 異常“getter functions must have no arguments”。

訊息

SyntaxError: Getter must not have any formal parameters. (V8-based)
SyntaxError: getter functions must have no arguments (Firefox)
SyntaxError: Unexpected identifier 'x'. getter functions must have no parameters. (Safari)

錯誤型別

SyntaxError

哪裡出錯了?

get 屬性語法看起來像一個函式,但它更嚴格,並非所有函式語法都允許。getter 總是以無引數方式呼叫,因此使用任何引數定義它可能是一個錯誤。

請注意,此錯誤僅適用於使用 get 語法的屬性 getter。如果你使用 Object.defineProperty() 等定義 getter,則 getter 將定義為普通函式,儘管如果 getter 期望任何引數,這仍然可能是一個錯誤,因為它將在不帶任何引數的情況下呼叫。

示例

無效案例

js
const obj = {
  get value(type) {
    return type === "string" ? String(Math.random()) : Math.random();
  },
};

有效情況

js
// Remove the parameter
const obj = {
  get value() {
    return Math.random();
  },
};

// Use a normal method, if you need a parameter
const obj = {
  getValue(type) {
    return type === "string" ? String(Math.random()) : Math.random();
  },
};

另見