add a private static property to a class in javascript

In order to add a private static property to a class in JavaScript, we need to use the JavaScript static keyword alongside the new # private field declaration.

Here's an example implementation:

index.tsx
class MyClass {
  static #privateStaticProperty = 'This is private static property';

  static getPrivateStaticProperty() {
    return this.#privateStaticProperty;
  }
}
170 chars
8 lines

In the above code, we've used the static keyword to declare a private static field called #privateStaticProperty. We've also created a static method called getPrivateStaticProperty to access this private static property.

Note that the # symbol is used to declare private fields in JavaScript. These fields are not accessible outside of the class they are declared in.

Now we can use the getPrivateStaticProperty method to access the private static property:

index.tsx
console.log(MyClass.getPrivateStaticProperty()); // Output: 'This is private static property'
94 chars
2 lines

Since the private static property is not directly accessible, using a getter method is the only way to access it.

gistlibby LogSnag