【问题标题】:How to access static members from instance methods in typescript?如何从打字稿中的实例方法访问静态成员?
【发布时间】:2015-05-28 10:36:55
【问题描述】:

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

【问题讨论】:

  • TLDR - ClassName.property。对于被覆盖的属性,(<typeof ClassName> this.constructor).property.

标签: typescript


【解决方案1】:

你只需要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。遗憾的是,您需要使用 some 类型的断言。我正在使用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]';
}

【讨论】:

  • 你的 more-gitbook 很棒。比 youtube 视频更容易消化(更容易/更快地阅读)。我错过了发布的日期时间戳。我怎么知道自从我上次看到该页面后发生了变化?
  • 我知道使用 ClassName.property。但是即使在定义了自己的 .PREFIX 的子类中,它也会使用 Logger.PREFIX。
  • 更新了问题以更清楚地了解预期结果。
  • @SimonHürlimann 更新了答案以考虑到这一点;)
  • 这不起作用。例如:``` const a = new Logger(); a.log('a') const b = new Warner(); b.log('b') ``` 两个日志信息
猜你喜欢
  • 1970-01-01
  • 2014-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-28
  • 2015-01-30
  • 2013-10-28
  • 2012-07-26
相关资源
最近更新 更多