typescript 如何从打字稿中的实例方法访问静态成员?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29244119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:58:41  来源:igfitidea点击:

How to access static members from instance methods in typescript?

typescript

提问by Simon Hürlimann

I try to use a static member from an instance method. I know about accessing static member from non-static function in typescript, but I do not want to hard code the class to allow inheritance:

我尝试使用实例方法中的静态成员。我知道从 typescript 中的非静态函数访问静态成员,但我不想对该类进行硬编码以允许继承:

class Logger {
  protected static PREFIX = '[info]';

  public log(msg: string) {
    console.log(Logger.PREFIX + ' ' + msg); // What to use instead of Logger` to get the expected result?
  }
}

class Warner extends Logger {
  protected static PREFIX = '[warn]';
}

(new Logger).log('=> should be prefixed [info]');
(new Warner).log('=> should be prefixed [warn]');

I've tried things like

我试过这样的事情

typeof this.PREFIX

回答by basarat

You simply need ClassName.property:

你只需要ClassName.property

class Logger {
  protected static PREFIX = '[info]';
  public log(message: string): void {
    alert(Logger.PREFIX + string); 
  }
}

class Warner extends Logger {
  protected static PREFIX = '[warn]';
}


MORE

更多的

from : http://basarat.gitbooks.io/typescript/content/docs/classes.html

来自:http: //basarat.gitbooks.io/typescript/content/docs/classes.html

TypeScript classes support static properties that are shared by all instances of the class. A natural place to put (and access) them is on the class itself and that is what TypeScript does:

TypeScript 类支持由类的所有实例共享的静态属性。放置(和访问)它们的自然位置是在类本身上,这就是 TypeScript 所做的:

class Something {
    static instances = 0;
    constructor() {
        Something.instances++;
    }
}

var s1 = new Something();
var s2 = new Something();
console.log(Someting.instances); // 2


UPDATE

更新

If you want it to inherit from the particular instance's constructor use this.constructor. Sadly you need to use sometype assertion. I am using typeof Loggershown below:

如果您希望它从特定实例的构造函数继承,请使用this.constructor. 遗憾的是,您需要使用某种类型断言。我正在使用typeof Logger如下所示:

class Logger {
  protected static PREFIX = '[info]';
  public log(message: string): void {
    var logger = <typeof Logger>this.constructor; 
    alert(logger.PREFIX + message); 
  }
}

class Warner extends Logger {
  protected static PREFIX = '[warn]';
}