Use the
classkeyword to create aThermostatclass. Theconstructoraccepts a Fahrenheit temperature.In the class, create a
getterto obtain the temperature in Celsius and asetterto set the temperature in Celsius.Remember that
C = 5/9 * (F - 32)andF = C * 9.0 / 5 + 32, whereFis the value of temperature in Fahrenheit, andCis the value of the same temperature in Celsius.Note: When you implement this, you will track the temperature inside the class in one scale, either Fahrenheit or Celsius.
This is the power of a getter and a setter. You are creating an API for another user, who can get the correct result regardless of which one you track.
In other words, you are abstracting implementation details from the user.
// Only change code below this line
class Thermostat {
constructor(temperature) {
this.temperature = temperature;
}
get temperature() {
return 5/9 * (this.temperature - 32);
}
set temperature(updatedTemperature) {
this.temperature = 9 * updatedTemperature / 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
Don’t know what is wrong with my code can someone please help?
>Solution :
You have to create a property, otherwise, you are referencing getter and setter while using this.temperature)
// Only change code below this line
class Thermostat {
_temperature = 0
constructor(temperature) {
this._temperature = temperature;
}
get temperature() {
return 5/9 * (this._temperature - 32);
}
set temperature(updatedTemperature) {
this._temperature = 9 * updatedTemperature / 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
console.log(temp)
You can create a private property by using #
// Only change code below this line
class Thermostat {
#temperature = 0
constructor(temperature) {
this.#temperature = temperature;
}
get temperature() {
return 5/9 * (this.#temperature - 32);
}
set temperature(updatedTemperature) {
this.#temperature = 9 * updatedTemperature / 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
console.log(temp)