You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修复Thermostat类代码:实现基于底层字段的Getter/Setter属性

Thermostat类代码的问题分析

这段代码存在两个核心问题:

1. 无限递归导致栈溢出

在get temperature()和set temperature()中,直接使用了this.temperature:

  • 调用thermos.temperature触发getter时,getter里的this.temperature会再次调用自身,形成无限递归
  • 执行thermos.temperature = 26触发setter时,setter里的this.temperature = ...会再次调用自身,同样陷入无限递归
    最终会抛出Maximum call stack size exceeded的错误。

2. 未隐藏内部温度存储的实现细节

题目要求类内部以单一温度单位存储温度,对外隐藏实现细节,但当前代码直接将温度暴露在this.temperature上,没有区分内部存储和对外的访问接口。


修复后的代码

// Only change code below this line
class Thermostat {
  constructor(temperature) {
    // 内部存储华氏温度,用下划线约定为私有变量
    this._temperature = temperature;
  }
  get temperature() {
    // 将内部存储的华氏温度转换为摄氏返回
    return 5/9 * (this._temperature - 32);
  }
  set temperature(updatedTemperature) {
    // 将传入的摄氏温度转换为华氏后存储到内部变量
    this._temperature = 9 * updatedTemperature / 5 + 32;
  }
}
// Only change code above this line

const thermos = new Thermostat(76); // Setting in Fahrenheit scale
let temp = thermos.temperature; // 24.44 in Celsius
thermos.temperature = 26;
temp = thermos.temperature; // 26 in Celsius

修复说明:

  • 使用this._temperature作为内部存储变量,避免与getter/setter的temperature名称冲突,彻底解决递归问题
  • 内部始终以华氏温度存储,对外通过getter返回摄氏温度、setter接收摄氏温度并转换为华氏存储,完全隐藏了内部的存储细节,符合题目要求

内容的提问来源于stack exchange,提问作者theonerishi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 10:42:39