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

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

本文介绍了如何从打字稿中的实例方法访问静态成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

更多

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

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

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:

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 如下所示:

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

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

这篇关于如何从打字稿中的实例方法访问静态成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:16