08. Class Fields

Class fields proposal add two features:

  • field declaration syntax

  • class initializers

Field declaration syntax

Field declarations:

  • public instance field;

  • private instance fields;

  • static fields.

class MyClass {
  instanceProperty = 0;
  static staticProperty = 0;
}

Private fields

class MyClass {
  #foo; // must be declared
  constructor(foo) {
    this.#foo = foo;
  }
  incFoo() {
    this.#foo++;
  }
}
  • Private fields have names starting with a # and are only visible within the body of the class.

  • In order to access a private field, you need to have defined it.

  • Referencing private fields works similar to accessing any other property, only it has a special syntax.

  • Private fields are managed via a data structure that is attached to objects.

  • If you are inside the body of a class; access to this does not give you access to private data.

Используется # а не ключевое слово private поскольку приватные данные не хранятся внутри объекта класса, а хранятся внутри специальной структуры данных, ассоциированной с объектом. Обращение this.# означает доступ в эту структуру данных, а не к самому объекту класса this.

С другой стороны, если мы обязаны задаваться вопросом - почему # и знать про внутреннюю структуру, то тогда private fields являются leaky abstraction.

Class initializers

With an initializer, you create a property and assign it a value at the same time. In the following code, = 0 is an initializer:

class MyClass {
  x = 0;
  y = 0;
}

This class is equivalent to:

class MyClass {
  constructor() {
    this.x = 0;
    this.y = 0;
  }
}

Initializers are executed before the constructor.

Last updated