How to inherit static methods from base class in JavaScript?

后端 未结 6 1583
长情又很酷
长情又很酷 2020-12-24 07:53

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.

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-24 08:11

    For ES5 you will need to use Object.assign to copy static methods from BaseClass to SubClass but for ES6 it should work without using Object.assign

    ES5 Example

    var BaseClass = function(){
    
    }
    
    BaseClass.sayHi = function(){
       console.log("Hi!");
    }
    
    var SubClass = function(){
    
    }
    
    Object.assign(SubClass , BaseClass);
    
    BaseClass.sayHi();   //Hi
    SubClass.sayHi(); //Hi

    ES6 Example

    class BaseClass {
       static sayHi(){
         console.log("Hi!");
       }
    }
    
    class SubClass extends BaseClass{
    
    }
    
    BaseClass.sayHi()   //Hi
    SubClass.sayHi() //Hi

提交回复
热议问题