SyntaxError: getter and setter for private name #x should either be both static or non-static

當私有 gettersetterstatic 屬性不匹配時,會發生 JavaScript 異常“放置不匹配”。

訊息

SyntaxError: Identifier '#x' has already been declared (V8-based)
SyntaxError: getter and setter for private name #x should either be both static or non-static (Firefox)
SyntaxError: Cannot declare a private non-static getter if there is a static private setter with used name. (Safari)

錯誤型別

SyntaxError

哪裡出錯了?

同名的私有 gettersetter 必須要麼都為 static,要麼都為非靜態。對於公共方法則沒有此限制。

示例

放置不匹配

js
class Test {
  static set #foo(_) {}
  get #foo() {}
}

// SyntaxError: getter and setter for private name #foo should either be both static or non-static

由於 foo私有的,因此這些方法必須要麼都為 static

js
class Test {
  static set #foo(_) {}
  static get #foo() {}
}

要麼都為非靜態

js
class Test {
  set #foo(_) {}
  get #foo() {}
}

另見