
Thermostat 类中的 Getter 和 Setter 方法:正确设置和获取温度
在 Thermostat 类中,使用 getter 和 setter 方法来控制成员变量的访问,确保数据的安全性和一致性。setter 方法用于设置变量值,而 getter 方法用于获取变量值。
问题及解决方案:
原始代码中 set temperature 方法存在问题,它缺少参数,无法正确设置温度值。
改进后的代码:
<code class="javascript">class Thermostat {
constructor(fahrenheit) {
this.celsius = 5/9 * (fahrenheit - 32);
}
get temperature() {
return this.celsius;
}
set temperature(celsius) {
this.celsius = celsius;
}
}</code>此版本代码中:
constructor 方法:接收华氏温度作为参数,并将其转换为摄氏温度,存储在 celsius 属性中。get temperature 方法:返回存储的摄氏温度。set temperature 方法:接收摄氏温度作为参数,并更新 celsius 属性的值。使用方法示例:
<code class="javascript">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</code>
通过以上改进,set temperature 方法能够正确接收和设置摄氏温度,从而确保 Thermostat 类能够准确地管理和操作温度值。 代码清晰地展示了如何使用 getter 和 setter 方法来封装数据,并提供了一种安全可靠的方式来访问和修改温度。
以上就是Thermostat类中getter和setter方法如何正确设置和获取温度?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号