ES6 - Use getters and setters to Control Access to an Object

Tell us what’s happening:
Hello everyone,

I’m having trouble understanding why my solution will not pass. I think I’m either misunderstanding the prompt or unclear on the function of the setter method.

“In the class, create a getter to obtain the temperature in Celsius and a setter to set the temperature in Celsius.”

I cannot tell why I am not ‘setting’ the temperature to celsius.

Your code so far

// Only change code below this line
class Thermostat {
  constructor(fahr) {
    this._fahr = fahr;
  }
  get temperature() {
    return (5/9 * (this._fahr - 32));
  }
  set temperature(celsius) {
    this._fahr = celsius;
  }
}
// Only change code above this line

const thermos = new Thermostat(76); // Setting in Fahrenheit scale
let temp = thermos.temperature; // 24.44 in Celsius
thermos.temperature = 26;
temp = thermos.temperature; // 26 in Celsius

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36

Challenge: ES6 - Use getters and setters to Control Access to an Object

Link to the challenge:

Should you assign a Celsius value to a variable that is supposed to hold a Fahrenheit value like that?

I wouldn’t think so, but I did take a look at the hint and the given example and they seem to use a similar method. Seems to me that the scope is limited?

What are you doing in this return statement?

As far as I can tell its returning a celsius value calculated from the fahrenheit property.

Didn’t the instruction give you a formula to convert the other way?

It does, I’m purely confused by the phrasing here.

“In the class, create a getter to obtain the temperature in Celsius and a setter to set the temperature in Celsius.”

Are you saying I need to set(calculate) the temp in fahrenheit with the celsius value?

I can see how it can be slightly confusing. The getter and setter are the public interfaces for the class. They always use Celsius. But how you actually store the temperature behind the scenes in the class is private, the outside world will never see it and doesn’t need to know.

This is how you are currently storing the temp in the class:

this._fahr = fahr;

You are storing in in F. So in the setter, even though the value being passed into it is in C, you need to store that internally in F, because that’s what this._fahr is using. So you probably need to make a conversion so you can do that.

As a side note, you don’t have to store the internal temp in F. There is nothing preventing you from storing it in C if that makes it easier for you to comprehend what is going on here.

Ok that makes a lot of sense. I can tell ill be spending a lot more time getting this concept under my belt. Thanks for your prompt and comprehensive response. Really appreciate it.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.