Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit static methods in ES6

Tags:

ecmascript-6

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);

like image 771
niftygrifty Avatar asked Apr 03 '15 21:04

niftygrifty


People also ask

Can we inherit static method in JS?

Static Methods Are Inherited When Using ES6 Extends Syntax In JavaScript And Node.

Do static properties get inherited?

Inheritance of static properties and methodsStatic properties and methods are inherited.

How is inheritance implemented in ES6?

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.

Can static method be inherited in subclass?

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.


1 Answers

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

like image 193
alexpods Avatar answered Oct 13 '22 16:10

alexpods