Javascript 如何重写函数以便在子类中使用
如何重写函数init,以便将其放置在父类中并在子类中调用。并将所需的函数传递给它。因为在类Javascript 如何重写函数以便在子类中使用,javascript,class,oop,asynchronous,promise,Javascript,Class,Oop,Asynchronous,Promise,如何重写函数init,以便将其放置在父类中并在子类中调用。并将所需的函数传递给它。因为在类GetWeatherForCurrentCity中,我们从方法getCoordinates获取位置,在类GetWeatherForRandomCity中,我们从方法getLocation获取位置 class Weather { async getCoordinates(city) { //code } async getLocation() { /
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);
});
}
}
只需在父类中移动函数,然后在子类中重新声明或覆盖它(这称为OOP概念之一的多态性)也许只需在父类中创建
init
函数并使用参数调用它?像这样:
班级天气{
异步获取坐标(城市){
//代码
}
异步getLocation(){
//代码
}
异步getWeatherForecast(位置坐标){
//代码
}
华氏摄氏度(温度){
//代码
}
renderForecastInfo(当前,每日){
//代码
}
初始(位置坐标){
此.getWeatherForecast(位置坐标)
。然后((预测)=>{
const{current,daily}=预测;
此.renderForecastInfo(当前,每日);
});
}
};
类GetWeatherForCurrentCity扩展天气{
init(){
this.getLocation()。然后((位置)=>{
Weather.prototype.init.call(这个,location.loc);
});
}
};
类GetWeatherForRandomCity扩展了Weather{
建造商(城市){
超级();
this.city=城市;
}
makeRandom(){
//代码
};
init(){
this.getCoordinates(this.makeRandom())。然后(coords=>{
Weather.prototype.init.call(this,coords);
});
}
}
我真诚地建议您不要在这里使用class
es和继承。让它成为一个简单的函数
,你可以调用,更加灵活。@Bergi在我的任务中,我不得不使用Inheritance,真遗憾。尽管如此,您仍然可以编写一个helper方法getAndRenderForecast
,将位置坐标作为参数,并在init
方法中调用该方法以避免代码重复。有关JS中多态性的更多信息,请参阅此链接