【发布时间】:2017-09-11 01:02:20
【问题描述】:
我正在使用 typescript,但类之间的静态继承存在问题
谁能解释一下下面的结果:
class Foo {
protected static bar: string[] = [];
public static addBar(bar: string) {
this.bar.push(bar);
}
public static logBar() {
console.log(this.bar);
}
}
class Son extends Foo {
protected static bar: string[] = [];
}
class Daughter extends Foo {}
Foo.addBar('Hello');
Son.addBar('World');
Daughter.addBar('Both ?');
Foo.logBar();
Son.logBar();
Daughter.logBar();
当前结果:
[ 'Hello', 'Both ?' ]
[ 'World' ]
[ 'Hello', 'Both ?' ]
但我想要:
[ 'Hello' ]
[ 'World' ]
[ 'Both ?' ]
我有没有重新声明静态bar 属性的解决方案?
谢谢!
【问题讨论】:
-
去掉static
-
删除
static会使属性绑定到实例而不是类型。 OP 希望属性绑定到类型。
标签: javascript typescript ecmascript-6 typescript2.0