Typescript类继承:覆盖ko.computed方法

 大乐电摩配销售中心 发布于 2023-02-07 19:11

我有简单的课程:

/// 
/// 

module Some.Namespace {

    export class TestBase {
        public field1: KnockoutObservable = ko.observable("");

        public onFieldChange: KnockoutComputed = ko.computed(() => {
            return this.field1();
        }, this);
    }

    export class Test extends TestBase {
        public field2: KnockoutObservable = ko.observable("");

        public onFieldChange() {
            super.onFieldChange() + this.field2();
        }
    }
}

问题,打字稿不允许在重写方法中使用关键字super.它说:

错误1类'Some.Namespace.Test'不能扩展类'Some.Namespace.TestBase':类'Some.Namespace.Test'定义实例成员函数'onFieldChange',但扩展类'Some.Namespace.TestBase'将其定义为实例成员属性.

错误2只能通过'super'关键字访问基类的公共方法.

如何覆盖knockout计算方法并且不松开基本方法?

1 个回答
  • 如果您自己定义相同的名称,则无法从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();
        }
    }
    

    2023-02-07 19:15 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有