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

时间:2015-03-24 22:31:21

标签: typescript

我尝试使用实例方法中的静态成员。我知道accessing static member from non-static function in 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

1 个答案:

答案 0 :(得分:23)

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

更多

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

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]';
}