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() {}
}

另见