1

How can I call a static method of a subclass from a static method of the parent class?

class A {

  static foo(){
    // call subclass static method bar()
  }
}

class B extends A {

  static bar(){
    // do something
  }
}

B.foo()

Update:

The reason why I tried this is that subclasses of A would have worked best as singletons in my context and I wanted to use the template method pattern in A.

Since it looks like I cannot get a reference to a subclass from a static context I am now exporting instances of subclasses of A which works just as well. Thanks.

Update 2

Yes, it is a duplicate to a degree (the other question does not involve subclassing). The reference, even from a static context, is this. So this works:

static foo(){
    this.bar();
}
hcvst
  • 2,665
  • 2
  • 22
  • 25
  • 1
    I believe you have javascript a bit confused, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes – Derek Pollard Aug 18 '16 at 06:51
  • Could @You point at a particular section, please? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Static_methods – hcvst Aug 18 '16 at 07:07
  • What are you trying to achieve? You haven't declared anything in the base class from the sub class. So the call `B.foo()` won't return anything. – Dandy Aug 18 '16 at 07:44
  • You seem to be looking for `this.bar()` - but notice that `A.foo()` won't work unless `A` has a `foo` method as well. – Bergi Aug 18 '16 at 08:03

2 Answers2

0

I am a bit confused to your need, as it seems you sorta already get what you need to do with B.foo(). So, is this what you need?

class A {

  static foo(){
    // call subclass static method bar()
    // Because it is "static" you reference it by just calling it via
    // the class w/o instantiating it.
    B.bar() 

  }
}

class B extends A {

  static bar(){
    // do something
    console.log("I am a static method being called")
  }
}

// because "foo" is static you can call it directly off of 
// the class, like you are doing
B.foo()

// or
var D = new B()
D.bar() // won't work ERROR
A.foo() // Works <-- Is this is specifically what you are asking? Or 
        // calling it in the Super class like B.bar(), that is done in static method foo?

Is this what you are asking? If this does not answer your question, please let me know what I am misunderstanding and I'll try to answer. Thanks.

james emanon
  • 11,185
  • 11
  • 56
  • 97
  • Thanks @james. Rather than calling `B.bar()` explicitly I would have liked to call something like `subClassRef.bar()` as `A` can have different subclasses. – hcvst Aug 18 '16 at 07:49
0

It makes the template pattern somewhat less elegant, but you can accomplish this via super in the subclass, eg:

class A {
  static foo() {
    this.bar()
  }
}

class B extends A {
  static foo() {
    super.foo()
  }
  static bar() {
    console.log("Hello from B")
  }
}

B.foo()
hunterloftis
  • 13,386
  • 5
  • 48
  • 50