请向我解释一下setter是如何在JavaScript中的类中工作的



目标:使用class关键字创建恒温器类。构造函数接受华氏温度。在该类中,创建一个getter以获得以摄氏度为单位的温度,创建setter以设置以摄氏度表示的温度。

到目前为止,这是我的代码:

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);

我知道正确的解决方案是将this.fahrenheit = temperatureInCelcius;更改为this.fahrenheit = (celsius * 9.0) / 5 + 32;

但我不明白为什么。有人告诉我,我的代码缺少一个转换。

我的问题是:

  1. 为什么需要将华氏温度转换为摄氏度
  2. 这一行到底发生了什么?thermos.temperature = 26;我的理解是,当编译器看到那一行时,它会在构造函数内调用这一行
set temperature (temperatureInCelcius){
this.fahrenheit = temperatureInCelcius;
}

然后将26放入参数(temperatureInCelcius)中,然后将this.fahrenheit的属性值设置为26。

只是想要一些解释,因为感觉我错过了什么。非常感谢您的帮助<3

执行temp = thermos.temperature;时,将调用get temperature(),而对于thermos.temperature = 26;,则调用set temperature()

// 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

最新更新