Search code examples
javascriptoopinheritancestatic

How to inherit static methods from base class in JavaScript?


I'm trying to achieve some basic OOP in JavaScript with the prototype way of inheritance. However, I find no way to inherit static members (methods) from the base class.

We can simulate the basic class model by using prototype:

SomeClass = function(){
    var private_members;

    this.public_method = function(){
        //some instance stuff..
    };
};

Class.static_method = function(){
    //some static stuff;
};

//Inheritance
SubClass = function(){ //sub-class definition };
SubClass.prototype = new Class();

However, SubClass doesn't inherit static_method from Class.


Solution

  • Try this:

    class BaseClass {
        static baseMethod () {
            console.log("Hello from baseMethod");
        }
    }
    
    class MyClass extends BaseClass {
        constructor(props) {
            super(props);
        }
    }
    
    Object.assign(MyClass, BaseClass);
    

    They key is Object.assign which should be everyone's new best friend. You can now call any base method from BaseClass using MyClass as follows:

    MyClass.baseMethod();
    

    You can see this live and in action on this pen.

    Enjoy!