ES6 - Call static method within a class

后端 未结 3 610
夕颜
夕颜 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:41

    Both of the answers here are correct and good, but I wanted to throw in an added detail based on this question title.

    When I saw "ES6 - Call static method within a class" it sounded like "call a static method (from a non-static method) within a class". Def not what the initial question asker is asking in the details.

    But for anyone who wants to know how to call a static method from a non-static method within a class you can do it like this:

    class MyClass {
        myNonStaticMethod () {
            console.log("I'm not static.")
            MyClass.myStaticMethod()
        }
    
        static myStaticMethod () {
            console.log("hey, I'm static!")
        }
    }
    
    MyClass.myStaticMethod() // will log "hey, I'm static!"
    
    const me = new MyClass()
    
    me.myNonStaticMethod() // will log "I'm not static" and then "hey, I'm static!"
    

    The idea is that the static method is can be called without creating a new instance of the class. That means you can call it inside of a instance's method the same way you'd call it outside of the instance.

    Again, I know that's not what the detail of the question was asking for, but this could be helpful other people.

提交回复
热议问题