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

Tell us what’s happening:

I thought I have the get and set methods defined, but I actually got it wrong, and it says that I don’t have it defined. Could you please assist me on where the error is?

Your code so far

// Only change code below this line
class Thermostat {
  constructor(tempFahrenheit) {
    this._tempFahrenheit = tempFahrenheit;
  }

  get tempCelsius() {
    return this._tempCelsius;
  }

  set tempCelsius(tempFahrenheit) {
    this._tempCelsius = 5/9 * (tempFahrenheit - 32);
  }
}
// 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/130.0.0.0 Safari/537.36

Challenge Information:

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

Hi @KoduFCC

To define the getter and setter carefully look at the example given.

Then compare it to your code.

Happy coding

the name for setter and getter must be temperature

I changed the name for the setter and getter to be ‘temperature.’ Here’s my edited code:

class Thermostat {
  constructor(temperature) {
    this._temperature = temperature;
  }

  get temperature() {
    return this._temperature;
  }

  set temperature(temperature) {
    this._temperature = 5/9 * (temperature - 32);
  }
}

‘When instantiated with a Fahrenheit value, Thermostat should set the correct temperature’ and ‘Calling the setter with a Celsius value should set the temperature’ are the feedback messages that need to be fixed. I’d like to know where I’m going wrong.

this need to return the value in celsius

Now I got it, but the last one is the issue.

Can you post your updated code please

Here it is:

class Thermostat {
  constructor(temperature) {
    this._temperature = temperature;
  }

  get temperature() {
    return 5/9 * (this._temperature - 32);
  }

  set temperature(temperature) {
    this._temperature = 5/9 * (temperature - 32);
  }
}

Set should accept a temperature in Celsius, right?

Would you use the same calculation for the setter and the getter?

Internally do you store the temp as C or F?

How are you testing this?

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

thermos.temperature = 26;
temp = thermos.temperature; // 26 in Celsius
console.log(temp)
>>-19.629629629629633