【发布时间】:2020-08-22 19:10:35
【问题描述】:
如何重写函数init,使其可以放在父类中,在子类中调用。并将所需的功能传递给它。因为在GetWeatherForCurrentCity 类中,我们从方法getCoordinates 中获取位置,而在GetWeatherForRandomCity 类中,我们从方法getLocation 中获取位置。
class Weather {
async getCoordinates(city) {
//code
}
async getLocation() {
//code
}
async getWeatherForecast(locationCoordinates) {
//code
}
fahrenheitToCelsius(temp) {
//code
}
renderForecastInfo(currently, daily) {
//code
}
};
class GetWeatherForCurrentCity extends Weather {
init() {
this.getLocation().then((location) => {
const { loc } = location;
return this.getWeatherForecast(loc);
}).then((forecast) => {
const { currently, daily } = forecast;
this.renderForecastInfo(currently, daily);
});
}
};
class GetWeatherForRandomCity extends Weather {
constructor(city) {
super();
this.city = city;
}
makeRandom() {
//code
};
init() {
this.getCoordinates(this.makeRandom()).then(coords => {
return this.getWeatherForecast(coords);
}).then((forecast) => {
const { currently, daily } = forecast;
this.renderForecastInfo(currently, daily);
});
}
}
【问题讨论】:
-
我真诚地建议你不要在这里使用
classes 和继承。只需将其设为简单的function即可调用,更加灵活。 -
@Bergi 关于我的任务我必须使用继承
-
真可惜。不过,您可以编写一个辅助方法
getAndRenderForecast,它将位置的坐标作为参数,并在您的init方法中调用它以避免代码重复。 -
了解更多关于 JS 中的多态性,请参阅此链接stackoverflow.com/questions/44391149/…
标签: javascript class oop asynchronous promise