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);
Static Methods Are Inherited When Using ES6 Extends Syntax In JavaScript And Node.
Inheritance of static properties and methodsStatic properties and methods are inherited.
We use the extends keyword to implement the inheritance in ES6. The class to be extended is called a base class or parent class. The class that extends the base class or parent class is called the derived class or child class.
Static method is inherited in subclass but it is not polymorphism. When you writing the implementation of static method, the parent's class method is over hidden, not overridden.
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
Here is the es6fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With