利用getter和setter方法有效管理Thermostat对象的温度访问
问题描述:
如何改进以下代码,使用getter和setter方法来安全地访问和修改Thermostat对象的温度?
现有代码:
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 摄氏度
登录后复制
解决方案:
原代码存在问题:setter方法缺少参数,无法正确设置温度。 为了更有效地控制温度访问,我们需要修改constructor和setter方法:
constructor方法: 将摄氏温度作为内部存储变量。setter方法: 接受一个摄氏温度参数,并进行赋值。 可以考虑添加输入验证,例如限制温度范围。
改进后的代码:
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.44thermos.temperature = 26;temp = thermos.temperature; // 26 摄氏度console.log(temp); // 输出 26thermos.temperature = 150; //尝试设置超出范围的温度temp = thermos.temperature;console.log(temp); // 输出 26 (温度未改变,并打印错误信息)
登录后复制
这个改进后的版本不仅正确地使用了getter和setter方法,还加入了温度范围的验证,使代码更加健壮和可靠。
以上就是如何用getter和setter方法有效控制Thermostat对象的温度访问?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2639425.html