Search code examples
javascriptclassthisgetter-settersetter

Please explain to me how a setter work inside a class in JavaScript


The Goal: Use the class keyword to create a Thermostat class. The constructor accepts a Fahrenheit temperature. In the class, create a getter to obtain the temperature in Celsius and a setter to set the temperature in Celsius.

Here's my code so far:

class Thermostat {
  constructor(fahrenheit){
    this.fahrenheit = fahrenheit;
  }

  get temperature(){
    const inCelcius = 5/9 * (this.fahrenheit - 32) ;
    return inCelcius;

  }

  set temperature (temperatureInCelcius){
    this.fahrenheit = temperatureInCelcius;
  }

}

const thermos = new Thermostat(76); // Setting in Fahrenheit scale
let temp = thermos.temperature; // should show 24.44 in Celsius
console.log(temp);
thermos.temperature = 26;
temp = thermos.temperature; // should show 26 in Celsius but right now showing -3.333
console.log(temp);

I know the correct solution is to change this.fahrenheit = temperatureInCelcius; into this.fahrenheit = (celsius * 9.0) / 5 + 32;

But I don’t understand why. I've been told that my code is missing a conversion.

My questions are:

  1. Why is there a need to convert Fahrenheit into celsius?
  2. What exactly happens in this line? thermos.temperature = 26; My understanding is that when the compiler sees that line, it invokes this line inside the constructor
set temperature (temperatureInCelcius){
    this.fahrenheit = temperatureInCelcius;
  }

and then put 26 into the argument (temperatureInCelcius), then set the property value of this.fahrenheit to 26.

Just want some explanation cause it feels like I am missing something. Would greatly appreciate your help! <3


Solution

  • When you do temp = thermos.temperature;, get temperature() is called and for thermos.temperature = 26; set temperature() is called.

    // thermos.temperature = 76
    const thermos = new Thermostat(76);
    
    // this calls get temperature() and return 24.44
    // 5/9 * (76 - 32) = 24.44
    let temp = thermos.temperature;
    
    console.log(temp); // 24.44
    
    // this calls set temperature() and sets thermos.temperature = 26
    thermos.temperature = 26;
    
    // this calls get temperature() and return -3.333
    // 5/9 * (26 - 32) = -3.333
    temp = thermos.temperature;
    
    console.log(temp); // -3.33