打字稿继承财产
问题描述:
的代码如下:打字稿继承财产
class BaseClass {
propertyA: KnockoutObservable<string> = ko.observable<string>();
constructor(message: string) {
this.propertyA.subscribe((newValue)=>{
console.log(newValue); // not run when change propertyA in ChildClassA instance.
});
}
}
class ChildClassA extends BaseClass {
propertyA: KnockoutObservable<string> = ko.observable<string>(); //remove it, the issue is solved.
}
我注意到,当ChildClassA具有命名为BaseClass的相同属性,propertyA订阅功能将无法运行。删除ChildClassA中的该行声明将解决该问题。
为什么?
答
这是因为你在ChildClassA
后重新分配this.propertyA
在BaseClass
分配给它当编译为JavaScript代码变得
var BaseClass = (function() {
function BaseClass(message) {
this.propertyA = ko.observable();
this.propertyA.subscribe(function (newValue) {
console.log(newValue); // not run when change propertyA in ChildClassA instance.
});
}
return BaseClass;
}());
var ChildClassA = (function (_super) {
__extends(ChildClassA, _super);
function ChildClassA() {
_super.apply(this, arguments);
this.propertyA = ko.observable(); //remove it, the issue is solved.
}
return ChildClassA;
}(BaseClass));
看到它在playground
当实例ChildClassA
你打电话给super
BaseClass
的结构体,其分配this.propertyA
并订阅听众。精细。调用super
但是经过正确的,你在ChildClassA
构造与线
this.propertyA = ko.observable(); //remove it, the issue is solved.
属性初始化移到构造,后super
电话重新分配this.propertyA
。
在Typescript中没有重写属性(通过继承)。