使用 class 关键字创建 Thermostat 类。构造函数接受华氏温度。
在类中,创建一个 getter 来获取摄氏温度,并创建一个 setter 来设置摄氏温度。
请记住,C = 5/9 * (F - 32) 和 F = C * 9.0 / 5 + 32,其中 F 是华氏温度值,C 是相同温度的摄氏温度值。
注意:当您实现此操作时,您将以一种标度(华氏度或摄氏度)跟踪类内的温度。
这就是 getter 和 setter 的力量。您正在为另一位用户创建 API,无论您跟踪哪个用户,他都可以获得正确的结果。
换句话说,您正在从用户那里抽象实现细节。
// 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
不知道我的代码有什么问题,有人可以帮忙吗?
您必须创建一个属性,否则,您在使用时会引用 getter 和 setter
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)
您可以使用
#
创建私有财产
// 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)