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

Can someone help me to understand the setter line here. Why do we convert to fahrenheit if we already passed this value through the constructor.

Your code so far

// Only change code below this line
class Thermostat {
  constructor (fahrenheit) {
    this._fahrenheit= fahrenheit;
  }
  //get
  get temperature() {
    return 5/9 * (this._fahrenheit - 32);
  }
  //set
  set temperature (celcius) {
    this._fahrenheit = celcius * 9.0 / 5 + 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

console.log(temp)

Your browser information:

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

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

Link to the challenge:

These are used at different times. Initially, when Thermostat object is created it takes the temperature in Fahrenheit. For changing temperature after that, setter will be used:

const thermos = new Thermostat(76);  // initial temperature
thermos.temperature = 26;  // changing temperature uses setter and Celsius

by changing temperature do you mean converting? I dont understand the purpose of converting to Fahrenheit if we already have the value

Not converting. Ie. some time passes, temperature is no longer as it was, and object needs to reflect that.

sorry I’m just not understanding the flow of this code. If time passes what temp is changed first? Does the user input a different temp in celcius and the function internally converts to fahrenheit to update the object.

Exactly this. The only way to change the internal temperature is to use the setter, which will make sure the saved temperature will be in correct units.

2 Likes

thanks so much for taking the time to explain to me. I understand now!

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