0

I have a super class Foo with a static method and an instance method which both console.log() a static property.

How can I get the static method to property reference the correct static property. As you can see here it is only referencing the super class property and not the sub class property.

class Foo{
    whoAmI(){
        console.log(this.constructor.someStaticVar)
    }
    static whoAmI_static(){
        console.log(Foo.someStaticVar) // is there a way to call the calling class and not the superclass here?
    }
}
Foo.someStaticVar = 'I am Foo'


class Bar extends Foo{

}
Bar.someStaticVar = 'I am Bar'



let barInstance = new Bar()
Bar.whoAmI_static()
barInstance.whoAmI()

Expected output:

I am Bar
I am Bar

Actual Output:

I am Foo
I am Bar
Sean256
  • 2,849
  • 4
  • 30
  • 39
  • Why do the methods have the same name? Are you trying to call a static method from outside the class? – adeneo Jul 26 '17 at 22:25
  • @adeneo I changed the name for clarity which does not effect the code. – Sean256 Jul 26 '17 at 22:26
  • Well, the `whoAmI_static` function still logs `Foo.someStaticVar`, and it always will. Unless you also change `Foo.someStaticVar` it's not going to produce any other result ? – adeneo Jul 26 '17 at 22:28
  • 2
    You could just replace `Foo` with `this` instead, and get the result you want – adeneo Jul 26 '17 at 22:29
  • https://jsfiddle.net/adeneo/gze6r2z9/2/ – adeneo Jul 26 '17 at 22:30

0 Answers0