Hi, I can’t identify what’s wrong with the code I have written.
I can’t pass the test -
Calling the setter with a Celsius value should set the temperature .
Hereby is the code -
class Thermostat{
constructor(Ftemp){
this._Ftemp = Ftemp;
}
get temperature(){
return 5/9 * (this._Ftemp - 32);
}
set temperature(CTemp) {
this._Ftemp = CTemp;
}
}
Inside your Thermostat class, you’re storing the temperature in Fahrenheit, so your setter needs to convert from Celsius to Fahrenheit.
One minor point - your variable names aren’t in camel case.
Using cTemp and fTemp (or tempF and tempC, which I think are more readable) would be better.
Not sure how much I understand. If we are using get to access the property, then why are we returning the converted celcius value in get?
I am assuming set functions modify the fahrenheit value to celcius.
From the logic above following code makes sense:
class Thermostat{
constructor(fTemp){
this._fTemp = fTemp;
}
get temperature(){
return this._fTemp;
}
set temperature(cTemp) {
cTemp = 5/9 * (this._fTemp - 32);
}
}
However, the correct code is:
class Thermostat{
constructor(fTemp){
this._fTemp = fTemp;
}
get temperature(){
return 5/9 * (this._fTemp - 32);
}
set temperature(cTemp) {
this._fTemp = cTemp * 9.0 / 5 + 32
}
}
Above, get is converting fTemp to cTemp., which looks like a job pf a setting function.
and set function is assigning value to fTemp by modifying cTemp to fTemp. Not sure what’s going on.
Well, the aim of this exercise is to demonstrate hiding the details of “how this is implemented”.
So, you (the developer) can choose whether you want to store the temperature in fahrenheit or celsius.
That’s what this part of the instructions means:
When you implement this, you will track the temperature inside the class in one scale, either Fahrenheit or Celsius.
You chose fahrenheit (because you stored a fahrenheit temperature in the constructor).
But you could have chosen to convert that temperature to celsius, and to store it as a celsius value.
The important point is that, the code that uses your Thermostat class doesn’t need to know which choice you made .
The developer of that code just needs to know
how to create a Thermostat object (i.e. supply a fahrenheit value)
and that calling the getter/setter will return/accept a celsius value.
It’s a bit of a contrived example, though.
So I really wouldn’t worry too much about this one - I think it will all make more sense when you’ve had some more practice with classes and objects.