【问题标题】:Typescript - call child method from parent classTypescript - 从父类调用子方法
【发布时间】:2016-03-09 15:36:38
【问题描述】:

我正在尝试从打字稿中的抽象父类调用子方法。但是我收到了这个错误:

未捕获的类型错误:this.activateMultiselect 不是函数

如何才能不出错?

代码如下:

interface iGetAreas {
    _areasList: Array<string>;
    _areas: KnockoutObservableArray<string>;
    _selectedArea: KnockoutObservable<string>;
    getAreas(geonameId: string);
    activateMultiselect();
}

abstract class AreaGetter implements iGetAreas {
    _areasList = [];
    _areas = ko.observableArray([]);
    _selectedArea = ko.observable('');

    abstract activateMultiselect();

    getAreas(geonameId){
        var self = this;
        self._areasList = [];
        $.ajax({
            url: `http://api.geonames.org/children?geonameId=${geonameId}&username=elion`
        }).then(function(allAreasXML) {
            var allAreasJSON = xml2json(allAreasXML);
            var allAreas = JSON.parse(allAreasJSON);
            if(allAreas.geonames.length) {
                for (var index = 1; index < allAreas.geonames.length - 1; index++) {
                self._areasList.push(allAreas.geonames[index].geoname);
                }
            } else {
                if(allAreas.geonames) {
                    self._areasList.push(allAreas.geonames.geoname);
                }
            }
            self._areas(self._areasList);
            this.activateMultiselect();
        });
    }
}

class RegionGetter extends AreaGetter {
    activateMultiselect() {
        $("#region-select").multiselect({
            buttonWidth: '100%',
            buttonContainer: '<div style="height: 64px;" />',
            buttonClass: 'none',
            onChange: function(option, checked, select) {
                alert('Changed region option ' + $(option).val() + '.');
            }
        });
    }
}

class TownGetter extends AreaGetter {
    activateMultiselect() {
        $("#town-select").multiselect({
            buttonWidth: '100%',
            buttonContainer: '<div style="height: 64px;" />',
            buttonClass: 'none',
            onChange: function(option, checked, select) {
                alert('Changed town option ' + $(option).val() + '.');
            }
        });
    }
}

【问题讨论】:

    标签: typescript


    【解决方案1】:

    未捕获的类型错误:this.activateMultiselect 不是函数

    错误不是因为child 类没有该功能。是因为你的this 输入有误:

    this.activateMultiselect();
    

    修复:

    self.activateMultiselect();
    

    更多

    PS:建议使用arrow 函数。 https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

    【讨论】:

    • 谢谢。我将其更改为箭头函数,并将.then( 更改为箭头函数。它的执行速度似乎较慢,但我不确定这一切是否都在我的脑海中。
    • 全部在脑海中。拥有self 意味着没有偏好差异? 此外,有效的代码可能会比崩溃的代码更慢¯\_(ツ)_/¯
    • 仅仅链接到您自己的库或教程并不是一个好的答案。链接到它,解释它为什么解决问题,提供如何解决问题的代码,并否认你编写了它,这样可以得到更好的答案。见:What signifies “Good” self promotion?
    猜你喜欢
    • 2017-11-09
    • 2012-02-22
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多