0

In the following snippet, I wish to have a class variable foo. Subclasses of A may or may not override the static variable foo. In the following example it prints undefined for all three print statements. How can I refer to the most recent static variable in the MRO? (i.e. I can't hardcode the class name in run because it maybe be subclassed).

class A {
   static foo = "default"
   run() {
      console.log(this.foo)  // this needs to point to this class here
   }
}

class B extends A {   
}

class C extends A {
   static foo = "overridden"   
}


a = new A()
a.run()  // Expecting "default"

b = new B()
b.run()  // Expecting "default"

c = new C()
c.run()  // Expecting "overridden"
run_the_race
  • 1,344
  • 2
  • 36
  • 62
  • 1
    Static properties are properties of the class itself, not properties of the instances (`this` in `run` refers to an instance). – Teemu Oct 31 '22 at 08:49

1 Answers1

2

From MDN

The static keyword defines a static method or property for a class, or a class static initialization block (see the link for more information about this usage). Neither static methods nor static properties can be called on instances of the class. Instead, they're called on the class itself.

You could, as per this answer, access the constructor of the instance like so:

class A {
   static foo = "default"
   run() {
      console.log(this.constructor.foo)
   }
}

class B extends A {   
}

class C extends A {
   static foo = "overridden"   
}


a = new A()
a.run()  // Expecting "default"

b = new B()
b.run()  // Expecting "default"

c = new C()
c.run()  // Expecting "overridden"

… but this is probably a design mistake and you shouldn't be making the property static in the first place.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335