我试图从typescript中的抽象父类调用子方法。但是我收到了这个错误:
未捕获的TypeError: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() + '.');
}
});
}
}
答案 0 :(得分:1)
未捕获的TypeError:this.activateMultiselect不是函数
错误不是因为child
类没有该函数。这是因为你的错误this
:
this.activateMultiselect();
修复:
self.activateMultiselect();
PS:建议使用arrow
功能。 https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html