I want to do this:
class Parent {
static myMethod1(msg) {
// myMethod2 is undefined
this.constructor.myMethod2(msg);
}
}
class Child extends Parent {
static myMethod2(msg) {
console.log('static', msg);
}
}
Child.myMethod1(1);
But it doesn't work. Is this possible some other way? I don't want to hard code Child.myMethod2 in Parent which I know would work since I want random child classes to be able to define/override the static method but call that method from the parent without prior knowledge of which class is the child.
myMethod2
is undefined because the code is wrong. this
is class constructor in static methods, and this.constructor
is the constructor of a constructor, i.e. Function
. It should be:
class Parent {
static myMethod1(msg) {
this.myMethod2(msg);
}
}
This is antipattern, because Parent
doesn't have myMethod2
, and Parent.myMethod1()
will result in error. It should either contain no-op myMethod2
, or be labeled as abstract class to never be accessed directly.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments