Thermostat 类中的 Getter 和 Setter 方法:正确设置和获取温度
在 Thermostat 类中,使用 getter 和 setter 方法来控制成员变量的访问,确保数据的安全性和一致性。setter 方法用于设置变量值,而 getter 方法用于获取变量值。
问题及解决方案:
原始代码中 set temperature
方法存在问题,它缺少参数,无法正确设置温度值。
改进后的代码:
class Thermostat {
constructor(fahrenheit) {
this.celsius = 5/9 * (fahrenheit - 32);
}
get temperature() {
return this.celsius;
}
set temperature(celsius) {
this.celsius = celsius;
}
}
此版本代码中:
constructor
方法:接收华氏温度作为参数,并将其转换为摄氏温度,存储在 celsius
属性中。get temperature
方法:返回存储的摄氏温度。set temperature
方法:接收摄氏温度作为参数,并更新 celsius
属性的值。使用方法示例:
const thermostat = new Thermostat(76); // 初始化为华氏 76 度
let temperature = thermostat.temperature; // 获取摄氏温度,约为 24.44 度
console.log(temperature); // 输出:24.44
thermostat.temperature = 26; // 设置摄氏温度为 26 度
temperature = thermostat.temperature; // 获取更新后的摄氏温度
console.log(temperature); // 输出:26
通过以上改进,set temperature
方法能够正确接收和设置摄氏温度,从而确保 Thermostat 类能够准确地管理和操作温度值。 代码清晰地展示了如何使用 getter 和 setter 方法来封装数据,并提供了一种安全可靠的方式来访问和修改温度。