Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading