Getters and Setters

by REPLY2SAGAR

JavaScript

class Temperature {
    constructor(celsius) {
        this.celsius = celsius;
    }

    get fahrenheit() {
        return (this.celsius * 9/5) + 32;
    }

    set fahrenheit(value) {
        this.celsius = (value - 32) * 5/9;
    }

    display() {
        console.log(`The temperature is ${this.celsius}°C or ${this.fahrenheit}°F.`);
    }
}

let temp = new Temperature(25);
temp.display();  // Outputs: The temperature is 25°C or 77°F.
temp.fahrenheit = 86;
temp.display();  // Outputs: The temperature is 30°C or 86°F.