override a private property on a subclass in javascript

In JavaScript, there is no official private property support, but some patterns use symbols or WeakMaps to mimic it. If you have a private property defined on a parent class, you can still override it on a subclass, but you need to access it through a public method or getter/setter that you can redefine. Here is an example:

index.tsx
const _value = new WeakMap();

class Parent {
  constructor(value) {
    _value.set(this, value);
  }
  
  getValue() {
    return _value.get(this);
  }
}

class Child extends Parent {
  setValue(newValue) {
    _value.set(this, newValue);
  }
}

const c = new Child('hello');
console.log(c.getValue()); // 'hello'
c.setValue('world');
console.log(c.getValue()); // 'world'
374 chars
23 lines

In this example, the _value property is defined as a private property using a WeakMap. It is only accessible through the getValue method, which retrieves it from the _value map associated with the current instance (this). On the Child class, we add a setValue method that does the same but with a new value. When we create a new Child instance, we can still retrieve the private value from the parent and change it through the child. By this approach, we are able to override the parent's private property in a child instance.

gistlibby LogSnag