ES6 - Call static method within a class

后端 未结 3 598
夕颜
夕颜 2020-11-27 04:21

I have this class which does an internal call to a static method:

export class GeneralHelper extends BaseHelper{
     static is(env){
          return config         


        
3条回答
  •  悲&欢浪女
    2020-11-27 04:31

    It's the same as calling a method on an ordinary object. If you call the GeneralHelper.isProd() method, the GeneralHelper will be available as this in the method, so you can use

    class GeneralHelper {
         static is(env) { … }
         static isProd(){
             return this.is('prod');
         }
    }
    

    This will however not work when the method is passed around as a callback function, just as usual. Also, it might be different from accessing GeneralHelper explicitly when someone inherits isProd from your class and overwrites is, InheritedHelper.isProd() will produce other results.

    If you're looking to call static methods from instance methods, see here. Also notice that a class which only defines static methods is an oddball, you may want to use a plain object instead.

提交回复
热议问题