override a private static property on a subclass in javascript

In JavaScript, we can't technically override private static properties on a subclass because they are inaccessible from outside the class. However, we can simulate an override behavior using closures and getters/setters.

Assuming we have a parent class with a private static property:

index.tsx
class Parent {
  static #privateProp = 'foo';
  
  static get privateProp() {
    return this.#privateProp;
  }
}
114 chars
8 lines

We can create a subclass that simulates an override behavior using a closure:

index.tsx
class Child extends Parent {
  static #privateProp = 'bar';
  
  static get privateProp() {
    return this.#privateProp || Parent.privateProp;
  }
}
150 chars
8 lines

In the Child class, we create a private static property with the same name as the parent class. We then define a getter for the property that returns the value of the subclass property if it exists, and falls back to the parent class property using the super keyword.

Now, if we call Child.privateProp, it will return 'bar', even though the parent class has a private static property with the same name. This simulates an override behavior.

gistlibby LogSnag