private class fields in javascript

Private class fields is a feature added in ES6 that allows you to declare private properties in a class. These properties cannot be accessed from outside the class or subclass.

To define a private class field in javascript, you can use the # symbol before the property name, like this:

index.tsx
class MyClass {
  #privateField = 42;

  getPrivateField() {
    return this.#privateField;
  }
}
98 chars
8 lines

In the example above, #privateField is a private field that can only be accessed within the scope of the MyClass class.

To access the private field from within the class, you can define a method that returns the value of the private field, like the getPrivateField() method above.

index.tsx
const myObject = new MyClass();
console.log(myObject.#privateField); // SyntaxError: Private field '#privateField' must be declared in an enclosing class
console.log(myObject.getPrivateField()); // 42
201 chars
4 lines

However, if you try to access the private field directly from outside the class, you will get a SyntaxError.

Private class fields provide a way to encapsulate data within a class, and prevent outside code from accessing or modifying it directly. This improves the overall robustness and maintainability of your JavaScript code.

gistlibby LogSnag