2

How can I reference constants within an inherited class so that -

  1. They use the "local" constant if one is defined within the current class

  2. They fallback on to the parent's constant definition

As an example, I'm wondering what I would fill each instance of ???? with below to achieve the expected printed result

class Parent {
  static MY_CONST = 'aaa';

  print() {
    /* Expected result: Prints `aaa` */
    console.log('????');
  }
}


class ChildOne extends Parent {
  static MY_CONST = 'bbb';

  print() {
    /* Expected result: Prints `bbb` */
    console.log('????');
  }
}


class ChildTwo extends Parent {
  print() {
    /* Expected result: Prints `aaa` */
    console.log('????');
  }
}
abhchand
  • 515
  • 6
  • 13
  • Does this answer your question? [JavaScript: Inheritance and Constant declaration](https://stackoverflow.com/questions/744452/javascript-inheritance-and-constant-declaration) – xy2 Sep 12 '20 at 03:54
  • What JavaScript are you using that has const instance fields? I wasn’t aware that that was part of any proposals. – Ry- Sep 12 '20 at 03:58
  • I meant to define them as `static` constants. Updated. – abhchand Sep 12 '20 at 14:45
  • Just refer to them as `Parent.MY_CONST`, `ChildOne.MY_CONST` and `ChildTwo.MY_CONST` - same as referring to static methods. Where it actually gets interesting is when the `print` method is inherited. – Bergi Sep 12 '20 at 14:56
  • What if I don't know the name of the current Class? It could be any number of child classes - is there a way to see if this current class has a constant and if not fall back to the parent? – abhchand Sep 12 '20 at 21:22
  • 1
    `this.constructor.MY_CONST` – Ry- Sep 13 '20 at 13:44

0 Answers0