So I just finished the Using Getters and Setters thermostat activity in ES6.
I’m having trouble understanding what is happening with the setter code.
// Only change code below this line
class Thermostat {
constructor(fahrenheit) {
this.fahrenheit = fahrenheit;
}
// getter
get temperature () {
return (5 / 9) * (this.fahrenheit - 32);
}
// setter
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
thermos.temperature = 26;
temp = thermos.temperature; // 26 in Celsius
I understand how const thermos = new Themostat(76); is being converted using the getter
What I am not clear about is whether it is passing a celsius temperature into the setter. It doesn’t appear to be, but I’m not sure. If it is passing a celsius temperature into the setter then how is it working?
Exactly. The getter/setter are handling the conversion in this case.
In general, getter/setters handle conversion, error checking, validation, etc. They provide abstraction, so the internal details of the object’s code can be changed but the person using the getter/setter will get the exact same result.
Okay, that makes sense. I think I was getting hung up on lack of parentheses. I assumed that to pass a value/string into the setter I would have to use parentheses to connect it with the word Celsius. Is there a reason that parentheses are not required for this?
I am not the right person to ask why parenthesis are not needed here. I know they are not needed, but I don’t have a super satisfying answer as to why. Hopefully someone will chime in with their deeper knowledge on the design of JavaScript.