JavaScript class static constants extension on instances

Ran into an interesting question from a coworker. We were working through surprising (to me) PHP behavior on the usage of self:: vs static::. It's a question of late binding and the accessor. For a PHP reference to get a class's extended constant value from the subclass, you had to use static::.

Then they asked me how it works in JavaScript as we're moving toward React (woo). Had to admit, I had no idea. While I do use JS classes, it's more composition than inheritance if possible. Still, it's useful to know. There's an example below, but the take away is this:

Static constants are somewhat second class, and shouldn’t be used for extension based overrides. Preference functions in javascript.

  1. class ClassA {
  2.     public static MY_VALUE = 'asdf';
  3.  
  4.     // Possible, but one hell of an awkward turtle.
  5.     // getOutput(){
  6.     //     // @ts-ignore // Required to allow for __proto__ access
  7.     //     return this.__proto__.constructor.MY_VALUE;
  8.     // }
  9.  
  10.     getOutput(){
  11.         return ClassA.MY_VALUE;
  12.     }
  13. }
  14.  
  15. class ClassB extends ClassA {
  16.     // Note that Storm doesn't even find this be an extended / overridden property
  17.     public static MY_VALUE = 'fdsa';
  18.  
  19.     // This shows extension.
  20.     getOutput(){
  21.         return ClassB.MY_VALUE;
  22.     }
  23. }
  24.  
  25. const a = new ClassA();
  26. const b = new ClassB();
  27.  
  28. describe('constants usage', () => {
  29.     it('a instance of ClassA', () => {
  30.         expect(a).toBeInstanceOf(ClassA)
  31.     });
  32.  
  33.     it('b instance of ClassB', () => {
  34.         expect(b).toBeInstanceOf(ClassB)
  35.     });
  36.  
  37.     it('a should return ClassA value of MY_Value', () => {
  38.         expect(a.getOutput()).toBe(ClassA.MY_VALUE)
  39.     });
  40.  
  41.     it('b should return ClassB value of MY_Value', () => {
  42.         expect(b.getOutput()).toBe(ClassB.MY_VALUE)
  43.     });
  44.  
  45. });
Tags: 

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.