"Thermostat should be able to be instantiated", can you help?

Tell us what’s happening:

I don’t know where I went wrong, can you help me out.

Your code so far


// Only change code below this line
class Thermostat{
constructor(value){
    if(value>=32)
    {
        this.value = value;
    }
    else
    {   
        let a = (value * (9.0/5)) + 32;
        this.value = a;
    }
}

get temperature(){
    let a = ((5/9) * this.value) - 32;
    return a;        
}

set temperature(value)
{
    this.value = value;
}
}
// 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/80.0.3987.149 Safari/537.36.

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

Link to the challenge:

1 Like

Let’s take this one step at a time. The instructions say:

" Use the class keyword to create a Thermostat class. The constructor accepts a Fahrenheit temperature."

So you are getting a value in F and you want to save it in the class variable this.value (personally, I would use a better name). You have to decide whether you want to store this value as F or C. Right now you are trying to do a little bit of both. So rewrite your constructor to store it as either F or C and then post your code again. And if you do store it as C make sure that your conversion formula is correct.

2 Likes

Thanks for helping me out.

1 Like

Thanks for the help! I ran into this issue too. Is there some concept we’re supposed to take away from this? Is there some subtle problem with object instantiation that is occurring when the code uses conditionals if… else…?

@hukxchen No; the error message is largely unhelpful. Most likely if you are getting this error message, it is because you have done a calculation incorrectly. Also, the problem is just written in a confusing way (IMO). Here is the key:

  • The constructor takes a FAHRENHEIT value
  • The getter must return a CELSIUS value
  • And counterintuitively, the setter TAKES a CELSIUS value; so make sure you keep this in mind when you store the value taken in by the setter (e.g., if you are storing the temperature as Fahrenheit within your class, you must convert the input value to Celsius first)