call a private static property on an instance of a class in javascript

In JavaScript, private static properties can be created using a closure and a Symbol. To call a private static property on an instance of a class, we need to provide an accessor method (a public method that returns the private static property). Here's an example:

index.tsx
const MySingleton = (() => {

  const _privateStaticProperty = Symbol('privateStaticProperty');

  class MySingleton {
    constructor() {
      if (MySingleton.instance) return MySingleton.instance;

      this.publicProperty = 'I am a public property';
      this[_privateStaticProperty] = 'I am a private static property';

      MySingleton.instance = this;
    }

    get privateStaticProperty() {
      return this[_privateStaticProperty];
    }
  }

  return MySingleton;

})();

const instance = new MySingleton();

console.log(instance.privateStaticProperty); // Output: "I am a private static property"
613 chars
27 lines

In this example, we created a singleton class MySingleton that has a private static property _privateStaticProperty. We also defined an accessor method privateStaticProperty that returns the private static property.

To call the private static property on an instance of MySingleton, we simply call the public privateStaticProperty method on the instance, which returns the private static property.

Note that the private static property _privateStaticProperty is defined using a Symbol to prevent changes to the property using the = operator or to access the property using Object.keys(), Object.values(), and Object.entries().

gistlibby LogSnag