11
我尝试从实例方法使用静态成员。我知道accessing static member from non-static function in typescript,但我不想硬代码的类,允许继承:像如何从打字稿中的实例方法访问静态成员?
typeof this.PREFIX
我尝试从实例方法使用静态成员。我知道accessing static member from non-static function in typescript,但我不想硬代码的类,允许继承:像如何从打字稿中的实例方法访问静态成员?
typeof this.PREFIX
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]');
我试过的东西你只需要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
打字稿类支持由该类的所有实例共享静态属性。一个自然的地方放(和访问),他们是在类本身,这就是打字稿做:
class Something {
static instances = 0;
constructor() {
Something.instances++;
}
}
var s1 = new Something();
var s2 = new Something();
console.log(Someting.instances); // 2
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]';
}
您的更多gitbook是令人敬畏的行为。更多消化,然后youtube视频(更容易/更快的阅读)。我错过了发布的日期时间戳。自从我上次看到该页面后,我怎么知道发生了变化? – xmojmr 2015-03-25 04:39:48
@xmojmr在这里添加您的电子邮件:http://basarat.gitbooks.io/typescript/ – basarat 2015-03-25 06:10:58
我知道如何使用ClassName.property。但是,即使在定义了自己的.PREFIX的子类中,它也会使用Logger.PREFIX。 – 2015-03-25 08:17:04