override a public property on a subclass in javascript

To override a public property on a subclass in JavaScript, you can do the following:

  1. Create a parent class with a public property that you want to override:
index.tsx
class Parent {
  constructor() {
    this.propertyToOverride = 'originalValue';
  }
}
86 chars
6 lines
  1. Create a child class that extends the parent class:
index.tsx
class Child extends Parent {
  constructor() {
    super();
    this.propertyToOverride = 'newValue';
  }
}
108 chars
7 lines
  1. In the child class's constructor, call super() to invoke the parent class's constructor and inherit its properties. Then, override the parent class's propertyToOverride property with a new value.

Now, if you create an instance of the Child class, you can access propertyToOverride which will return the overridden value 'newValue'.

index.tsx
const child = new Child();
console.log(child.propertyToOverride); // outputs 'newValue'
88 chars
3 lines

gistlibby LogSnag