Use getters and setters to Control Access to an ObjectPassed

What if I put calculation to celsius in constructor?
It’s passes the tests so… is it really acceptable?

// Only change code below this line
class Thermostat{
    constructor(temp){
        this._temp=5/9 * (temp - 32);
    }

    get temperature(){
        //console.log(5/9 * (this._temp - 32))
        return this._temp
    }

    set temperature(newTemp){
     return this._temp = newTemp
     console.log(newTemp)
    }
}
// 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

Yes, it is. Class is still using Fahrenheit when object is initially instantiated and Celsius when temperature is set directly. Because of using getter and setter you can decide in which unit temperature is kept internally, while from the outside class is working the same.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.