Search code examples
javascriptclassstaticprivateclass-fields

Private class field in JavaScript


class A {
  #a = 1;
  static #a = 2;
}

Results in

  • Uncaught SyntaxError: redeclaration of private name #a in Firefox
  • Uncaught SyntaxError: Identifier '#a' has already been declared in Chrome

While

class A {
  a = 1;
  static a = 2;
}

is valid in both Firefox and Chrome

AFAIK instance fields will be installed on the class instance while static fields will be installed on the class object itself. They are not conflicted. Why the former code is invalid?


Solution

  • Instance fields will be installed on the class instance while static fields will be installed on the class object itself. They are not conflicted.

    They are, because in the expression x.#a the engine doesn't know whether x is a class object or a class instance. The meaning of the #a token should be static and not depend on the object, it needs to refer to the one or to the other but not to both.

    Unlike normal string-keyed properties that are identified by the string value of the identifier (.a is the same as .a regardless of context), private fields have an identity (not unlike symbols) that is created with their declaration. Only one #a can exist per class definition, and in a different class the same #a syntax will refer to a different field.