代码如下:
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中的声明行将解决此问题。
为什么?
这是因为你重新分配this.propertyA
在ChildClassA
后,在分配给它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));
在操场上看
实例化时,ChildClassA
您正在调用super
,后者调用的构造函数BaseClass
来分配this.propertyA
和订阅侦听器。美好的。然而正确调用之后super
,你重新分配this.propertyA
在ChildClassA
构造函数与线
this.propertyA = ko.observable(); //remove it, the issue is solved.
super
调用后,属性初始化将移至构造函数。
Typescript中没有诸如覆盖属性(通过继承)之类的东西。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句