Reputation: 3652
Using ES6 syntax is it possible to extend a class and inherit its static methods? And if so, can we call super in the subclass's static method?
Example:
class Parent {
static myMethod(msg) {
console.log(msg)
}
}
class Child extends Parent {
static myMethod() {
super("hello")
}
}
Child.myMethod(); // logs "hello"
This is giving me a no method call on undefined error in my transpiler (Reactify).
____SuperProtoOfParent.open.call(this);
Upvotes: 18
Views: 8063
Reputation: 48535
According to the spec here and here super
base references to the prototype of the current this
object. In static methods it will reference to the inherited class . So to invoke the parent static method you must call super.myMethod('some message')
. Here is an example:
class Parent {
static myMethod(msg) {
console.log('static', msg);
}
myMethod(msg) {
console.log('instance', msg);
}
}
class Child extends Parent {
static myMethod(msg) {
super.myMethod(msg);
}
myMethod(msg) {
super.myMethod(msg);
}
}
Child.myMethod(1); // static 1
var child = new Child();
child.myMethod(2); // instance 2
Upvotes: 25