我有简单的课程:
/// <reference path="..\typings\jquery\jquery.d.ts"/>
/// <reference path="..\typings\knockout\knockout.d.ts"/>
module Some.Namespace {
export class TestBase {
public field1: KnockoutObservable<string> = ko.observable("");
public onFieldChange: KnockoutComputed<string> = ko.computed(() => {
return this.field1();
}, this);
}
export class Test extends TestBase {
public field2: KnockoutObservable<string> = ko.observable("");
public onFieldChange() {
super.onFieldChange() + this.field2();
}
}
}
问题,打字稿不允许在重写方法中使用关键字super。它说:
错误1类'Some.Namespace.Test'无法扩展类 'Some.Namespace.TestBase':类'Some.Namespace.Test'定义 实例成员函数'onFieldChange',但扩展类 'Some.Namespace.TestBase'将其定义为实例成员属性。
错误2只能通过以下方法访问基类的公共方法 '超级'关键字。
如何覆盖knockout计算方法并且不松开基本方法?
答案 0 :(得分:5)
如果您自己定义相同的名称,则无法从TypeScript中的子类访问父实例成员属性。例如以下内容:
class TestBase {
public field1;
public onFieldChange = () => { // we need a way to reference this in the child
return this.field1();
};
}
class Test extends TestBase {
parentOnFieldChange:any;
constructor(){
super(); // call super
// Implictly initialize local properties
// copies local version not parent
this.parentOnFieldChange = this.onFieldChange;
}
public field2;
public onFieldChange = () => {
this.parentOnFieldChange() + this.field2();
}
}
生成(细分):
function Test() {
var _this = this;
_super.call(this); // call super
// NO WAY to put code here
// Implictly initialize local properties
this.onFieldChange = function () {
_this.parentOnFieldChange() + _this.field2();
};
// OUR code on only added after
// copies local version not parent
this.parentOnFieldChange = this.onFieldChange;
}
解决方案使用实例成员函数:
class TestBase {
public field1;
public onFieldChange() {
return this.baseOnFieldChange();
}
private baseOnFieldChange = () => { // we need a way to reference this in the child
return this.field1();
};
}
class Test extends TestBase {
parentOnFieldChange:any;
constructor(){
super(); // call super
}
public field2;
public onFieldChange(){
return super.onFieldChange() + this.childOnFieldChange();
}
private childOnFieldChange = () => {
return this.field2();
}
}