You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript开发天气API应用时类继承失效,出现Uncaught ReferenceError错误求助

嘿,我来帮你拆解下遇到的问题,一步步解决:

1. 解决 Weather is not defined 错误

这个问题的根源很简单——你在代码最顶部就尝试创建Weather类的实例,但JavaScript的类声明不会被提升(和普通函数不一样)。当浏览器执行到const weather = new Weather('Boston', 'MA')这行时,还没读到后面的Weather类定义,自然会报错。

修复方法:把Weather类的定义移到实例化代码的前面,调整后的代码结构如下:

// 先定义Weather类
class Weather {
  constructor(city, state) {
    this.apiKey = 'b4d8**';
    this.city = city;
    this.state = state;
  };

  // 从API获取天气数据
  async getWeather() {
    // 补全https前缀,修正参数格式
    const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${this.city},${this.state}&appid=${this.apiKey}`);
    const responseData = await response.json();
    // OpenWeatherMap没有current_observation字段,直接返回完整响应或按需取值
    return responseData;
  };

  // 修改天气查询地点
  changeLocation(city, state) {
    this.city = city;
    this.state = state;
  };
}

// 再初始化weather对象
const weather = new Weather('Boston', 'MA');

// DOM加载时获取天气数据
document.addEventListener('DOMContentLoaded', getWeather);
// weather.changeLocation('Miami', 'FL');

function getWeather(){
  weather.getWeather()
    .then(results => {
      console.log(results);
    })
    .catch(err => console.log(err));
}
2. 解决 Climate is not defined 错误

你提供的代码里并没有出现Climate类,但既然你提到想实现类继承功能,推测是你打算创建一个继承自Weather的Climate类但没定义。如果是这样,你可以这样写:

// 继承Weather类的Climate类
class Climate extends Weather {
  constructor(city, state, forecastDays) {
    super(city, state); // 调用父类的构造函数,继承city、state和apiKey
    this.forecastDays = forecastDays; // 添加子类独有的属性
  }

  // 子类特有的方法:获取多日气候预测
  async getClimateForecast() {
    const response = await fetch(`https://api.openweathermap.org/data/2.5/forecast?q=${this.city},${this.state}&cnt=${this.forecastDays}&appid=${this.apiKey}`);
    return await response.json();
  }
}

// 现在实例化Climate就不会报错了
const climate = new Climate('Boston', 'MA', 7);
额外的API细节修复

顺便帮你修正两个API调用的小问题,避免后续踩坑:

  • 你的fetch URL缺少https://前缀,浏览器会把它当成当前网站的相对路径请求,肯定会失败,必须补上。
  • OpenWeatherMap的响应里没有current_observation字段(这个是Weather Underground等其他API的结构),你可以直接返回responseData查看完整响应,或者根据需求提取responseData.main(温度、湿度等核心数据)、responseData.weather(天气状况描述)这类字段。

内容的提问来源于stack exchange,提问作者Sajid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 08:37:27