打字稿继承属性

艾玛

代码如下:

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中的声明行将解决此问题。

为什么?

布鲁诺·格里德(Bruno Grieder)

这是因为你重新分配this.propertyAChildClassA 后,在分配给它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.propertyAChildClassA构造函数与线

this.propertyA = ko.observable(); //remove it, the issue is solved.

super调用后,属性初始化将移至构造函数

Typescript中没有诸如覆盖属性(通过继承)之类的东西。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章