Rabten Tenzing
Rabten Tenzing

Reputation: 1

Can't read property 'weather' of undefined javascript in weather app

Thanks for everything guys, i had it right the first time but because of something else i kept getting confused and was trying to fix something that wasn't broken lol.

Upvotes: 0

Views: 85

Answers (2)

Ruan Mendes
Ruan Mendes

Reputation: 92284

The first one is accessing a variable that you've defined, called data. The second one is trying to use this.data which was never defined.

It's hard to tell why you think it should work.

It will work if you remove this. from this.data, but that doesn't really make sense, since you usually avoid accessing a global variable from inside an object

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68665

First one works because your are trying to access to global data object, which is initialized. And in the constructor you pass already got description

var data = JSON.parse(http.responseText);
var weatherData = new Weather(cityName, data.weather[0].description.toUpperCase());`

function Weather(cityName, description) {
    this.cityName = cityName
    this.description = description;
    this._temperature = '';
}

In the second case you are tring to access this.data.weahter, but you don't have any this.data in your object

var data = JSON.parse(http.responseText);
var weatherData = new Weather(cityName, data);

function Weather(cityName, datacity) {
    this.cityName = cityName
    this.data.weather[0].description.toUpperCase() = description;
      // ^ here your don't have data object, also neithier the weather for accessing by index

    this._temperature = '';
}

I think you only mistyped the property names and you need

var data = JSON.parse(http.responseText);
var weatherData = new Weather(cityName, data);

function Weather(cityName, datacity) {
    this.cityName = cityName
    this.description = datacity.weather[0].description.toUpperCase();
    this._temperature = '';
}

Upvotes: 1

Related Questions