
利用 Getter 和 Setter 方法优化对象属性访问
面向对象编程中,Getter 和 Setter 方法是控制对象属性访问和修改的关键。它们能够有效保护对象内部数据,同时提供受控的访问方式。
以下以 Thermostat 类为例,该类包含一个名为 farenheit 的成员变量,用于存储华氏温度。我们将使用 Getter 和 Setter 方法改进其访问控制。
原始代码示例:
<code class="javascript">class thermostat {
constructor(farenheit) {
this.farenheit = 5 / 9 * (farenheit - 32);
}
get temperature() {
return this.farenheit;
}
set temperature(farenheit) {
this.farenheit = farenheit;
}
}</code>改进后的代码:
<code class="javascript">class thermostat {
constructor(farenheit) {
this.celsius = 5 / 9 * (farenheit - 32);
}
get temperature() {
return this.celsius;
}
set temperature(celsius) {
this.celsius = celsius;
}
}</code>改进说明:
celsius,更准确地反映其存储的是摄氏温度。celsius 参数,允许外部代码修改该变量。使用方法:
<code class="javascript">const thermos = new Thermostat(76); // 设置华氏温度 let temp = thermos.temperature; // 获取摄氏温度 (约 24.44) thermos.temperature = 26; // 设置摄氏温度 temp = thermos.temperature; // 获取更新后的摄氏温度 (26)</code>
通过 Getter 和 Setter 方法,我们增强了对 celsius 变量的访问控制,同时保留了外部代码修改其值的灵活性。 这种方法提高了代码的可维护性和安全性。
以上就是如何使用Getter和Setter方法更好地控制Thermostat类的温度访问?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号