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

Sim*_*ann 18 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]');
Run Code Online (Sandbox Code Playgroud)

我尝试过类似的东西

typeof this.PREFIX
Run Code Online (Sandbox Code Playgroud)

bas*_*rat 33

你只需要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]';
}
Run Code Online (Sandbox Code Playgroud)

更多

来自: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
Run Code Online (Sandbox Code Playgroud)

UPDATE

如果您希望它继承特定实例的构造函数使用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]';
}
Run Code Online (Sandbox Code Playgroud)

  • 我知道如何使用 ClassName.property。但是即使在定义了自己的 .PREFIX 的子类中,它也会使用 Logger.PREFIX 。 (5认同)
  • 这是行不通的。例如: ``` const a = new Logger(); a.log('a') const b = new Warner(); b.log('b ') ``` 两者都记录信息 (4认同)