accessing static member from non-static function in typescript

社会主义新天地 提交于 2020-01-13 09:08:34

问题


I am trying to access a static member from a non-static function in the class, and I get an error saying

Static member cannot be accessed off an instance variable

this is how my code looks -

class myClass {
  public static testStatic: number = 0;
  public increment(): void {
    this.testStatic++;
  }
}

From what I understand of static members/methods, we shouldn't access non-static members in static functions, but vice-versa should be possible. the static member is already created and is valid, so why can't I access from my non-static method?


回答1:


Access static members from inside the class the same way you would from outside the class:

class myClass {
  public static testStatic: number = 0;
  public increment(): void {
    myClass.testStatic++;
  }
}



回答2:


I personally prefer something in the spirit of:

class myClass{
    public static testStatic: number = 0;
    private class;

    constructor(){
        this.class = myClass;
    }

    public increment(): void {
        this.class.testStatic++;
    }
}

One cool thing is that typescript is actually allowing me to use 'class' as a variable.




回答3:


For allowing inheritance you must use inside a instance method in order to don't repeat className:

<typeof ParentClass>this.constructor

See the Update section in this answer: https://stackoverflow.com/a/29244254/1936549



来源:https://stackoverflow.com/questions/22516320/accessing-static-member-from-non-static-function-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!