How to Declare a Private Field in an Enclosing Class in JavaScript?

Estimated read time 1 min read

In JavaScript, there is no built-in syntax for declaring private fields in an enclosing class, but there are a few common patterns for achieving private fields.

One pattern is to use closure and an immediately invoked function expression (IIFE):

class MyClass {
  constructor() {
    let privateField = "private value";
    this.getPrivate = () => privateField;
  }
}

let myClass = new MyClass();
console.log(myClass.getPrivate()); // "private value"

In this example, the private field privateField is declared inside the constructor function and is only accessible through the getPrivate method, which returns the value of privateField. This pattern makes the privateField value effectively private, as it is not directly accessible from outside the class.

Another pattern is to use WeakMap:

const _privateField = new WeakMap();

class MyClass {
  constructor() {
    _privateField.set(this, "private value");
  }

  getPrivate() {
    return _privateField.get(this);
  }
}

let myClass = new MyClass();
console.log(myClass.getPrivate()); // "private value"

In this example, the private field privateField is stored in a WeakMap with the current instance of the class as the key. The getPrivate method then retrieves the value of privateField from the WeakMap. This pattern also makes the privateField value effectively private, as it is not directly accessible from outside the class.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply