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



我尝试使用实例方法中的静态成员。我知道从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]');

我试过之类的东西

typeof this.PREFIX

您只需要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]';
}

更多

发件人:https://basarat.gitbook.io/typescript/future-javascript/classes

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

class Something {
    static instances = 0;
    constructor() {
        Something.instances++;
    }
}
var s1 = new Something();
var s2 = new Something();
console.log(Someting.instances); // 2

更新

如果希望它从特定实例的构造函数继承,请使用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]';
}

最新更新