使用 getter 和 setter 来控制对象的访问?-灵析社区

sssssjkl

## 使用 getter 和 setter 来控制对象的访问 使用 class 关键字创建一个 Thermostat class。 constructor 接收一个华氏温度. 记得在 C = 5/9 _(F - 32) 和 F = C_ 9.0 / 5 + 32 中,F 是华氏温度值,C 是摄氏温度值。 下面代码应该怎么修改? // 只修改这一行下面的代码 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 摄氏度 thermos.temperature = 26; temp = thermos.temperature; // 26 摄氏度 已经自己解决 set temperature(farenheit){ this.farenheit=farenheit; } 需要参数

阅读量:16

点赞量:0

问AI
不太明白你要干什么 1. 你的 "constructor",看起来是接收了一个华氏度然后转成摄氏度保存起来 那既然是摄氏度 为什么这个成员叫 "farenheit" 2. 你的 "set temperature" 没有接收参数,这是跑不起来的。 class Thermostat { constructor(farenheit) { this.celsius = 5/9 * (farenheit - 32) } get temperature() { return this.celsius } set temperature(celsius) { this.celsius = celsius; } } "image.png" (https://wmlx-new-image.oss-cn-shanghai.aliyuncs.com/images/20241103/3879c8bf3d873861975c57e5f1a4b576.png)