🥦Private class fields

A private class field is a class member (a field or a method) that can only be accessed from within the class. It is declared directly in the class, rather than inside a method.

Private class fields are prefixed with a # symbol.

Here is an example of a class with a private field:

class Counter {
  #count = 0;  // This is a private field

  // This is a public method
  increment() {
    this.#count++;
  }

  // This is a public method
  getCount() {
    return this.#count;
  }
}

const counter = new Counter();

// The private field cannot be accessed from outside the class
console.log(counter.#count);  // Output: Uncaught SyntaxError: Private field '#count' must be declared in an enclosing class

// We can only access the private field through the public methods
counter.increment();
counter.increment();
console.log(counter.getCount());  // Output: 2

In this example, the Counter class has a private field called #count and public methods increment and getCount. The private #count field is used to store the current count, and can only be accessed and modified from within the class. The public increment method is used to increase the count by 1, and the public getCount method is used to get the current count.

Private fields and methods can be useful for encapsulation, as they allow you to hide implementation details and prevent direct modification of sensitive data.

Private class fields and methods are a relatively new feature in JavaScript, and are currently only supported in certain modern browsers and when using certain language transpilers (such as Babel).

Last updated