语法错误:不能删除私有字段

JavaScript 异常“SyntaxError:当 delete 用于类或对象的 私有属性 时,会出现“无法删除私有字段”的情况。

¥The JavaScript exception "SyntaxError: private fields can't be deleted" occurs when delete is used on a private property of a class or an object.

信息

¥Message

SyntaxError: Private fields can not be deleted (V8-based)
SyntaxError: private fields can't be deleted (Firefox)
SyntaxError: Cannot delete private field X (Safari)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

有代码试图 delete 对象或类的私有属性(字段或方法)。这是 Javascript 禁止的 - 私有属性不能动态添加或删除。

¥There's code trying to delete a private property (field or method) of an object or a class. This is forbidden by Javascript—private properties cannot be added or removed on the fly.

示例

¥Examples

js
class MyClass {
  #myPrivateField;
  deleteIt() {
    delete this.#myPrivateField; // SyntaxError: private fields can't be deleted
  }
}
js
class MyClass {
  #myPrivateMethod() {
  }
  #deleteIt() {
    delete this.#myPrivateMethod; // SyntaxError: private fields can't be deleted
  }
}

也可以看看

¥See also