
利用getter和setter方法有效管理Thermostat对象的温度访问
问题描述:
如何改进以下代码,使用getter和setter方法来安全地访问和修改Thermostat对象的温度?
现有代码:
<code class="javascript">class thermostat {
constructor(farenheit) {
this.farenheit = 5/9 * (farenheit - 32);
}
get temperature() {
return this.farenheit;
}
set temperature() {
this.farenheit = farenheit;
}
}
const thermos = new thermostat(76); // 设置为华氏温度
let temp = thermos.temperature; // 24.44 摄氏度</code>解决方案:
原代码存在问题:setter方法缺少参数,无法正确设置温度。 为了更有效地控制温度访问,我们需要修改constructor和setter方法:
constructor方法: 将摄氏温度作为内部存储变量。setter方法: 接受一个摄氏温度参数,并进行赋值。 可以考虑添加输入验证,例如限制温度范围。改进后的代码:
<code class="javascript">class Thermostat {
constructor(fahrenheit) {
this.celsius = 5/9 * (fahrenheit - 32);
}
get temperature() {
return this.celsius;
}
set temperature(celsius) {
// 添加温度范围验证,例如限制在0到100摄氏度之间
if (celsius >= 0 && celsius <= 100) {
this.celsius = celsius;
} else {
console.error("温度设置超出范围 (0-100摄氏度)");
}
}
}
const thermos = new Thermostat(76); // 设置为华氏温度
let temp = thermos.temperature; // 24.44 摄氏度
console.log(temp); // 输出 24.44
thermos.temperature = 26;
temp = thermos.temperature; // 26 摄氏度
console.log(temp); // 输出 26
thermos.temperature = 150; //尝试设置超出范围的温度
temp = thermos.temperature;
console.log(temp); // 输出 26 (温度未改变,并打印错误信息)</code>这个改进后的版本不仅正确地使用了getter和setter方法,还加入了温度范围的验证,使代码更加健壮和可靠。
以上就是如何用getter和setter方法有效控制Thermostat对象的温度访问?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号