Tell us what’s happening:
Describe your issue in detail here.
Hello, I am new to JS (so maybe my question makes no sense).
Bellow is the correct answer for the challenge. However, my question is why when I typed at the end of the code: console.log(thermos.temperature) it gives 26 and does not use the equation in the setter? what’s the point of the equation in the setter if its not being used?
**Your code so far**
// Only change code below this line
class Thermostat {
constructor(fahrenheit) {
this.fahrenheit = fahrenheit;
}
get temperature() {
return (5 / 9) * (this.fahrenheit - 32);
}
set temperature(celsius) {
this.fahrenheit = (celsius * 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
console.log(thermos.temperature);
thermos.temperature = 26;
temp = thermos.temperature; // 26 in Celsius
console.log(thermos.temperature)
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36 OPR/81.0.4196.61
Challenge: Use getters and setters to Control Access to an Object
Yeah, it’s a little confusing, but when you reference thermos.temperature, if you are assigning a value, it calls the setter, if you are retrieving the value, it calls the getter. In some languages, you call the functions yourself. JS decide that you would just access it like it is a property and JS would figure out what to do, behind the scenes.
Put the celsius formula in the constructor function as a value of this.fahrenheit, and use the parameter inside the formula, the setter and getter look cleaner with the job already done for them.
I think.
That probably would be a “smoother” implementation - to only make the conversion with the constructor and just store the value as celsius.
That makes more sense in terms of clean code. I suppose they wanted it this way to show that getters and setters can do more than just being a passthrough for class property.
I’ve always kind of hated this challenge - it seems unnecessarily confusing. But I also can’t think of a better one without losing some of the educative value or making things too complex.