请向我解释一下 JavaScript 中的 setter 如何在类中工作
目标:使用 class 关键字创建 Thermostat 类。构造函数接受华氏温度。在该类中,创建一个 getter 来获取摄氏温度,并创建一个 setter 来设置摄氏温度。
到目前为止,这是我的代码:
class Thermostat {
constructor(fahrenheit){
this.fahrenheit = fahrenheit;
}
get temperature(){
const inCelcius = 5/9 * (this.fahrenheit - 32) ;
return inCelcius;
}
set temperature (temperatureInCelcius){
this.fahrenheit = temperatureInCelcius;
}
}
const thermos = new Thermostat(76); // Setting in Fahrenheit scale
let temp = thermos.temperature; // should show 24.44 in Celsius
console.log(temp);
thermos.temperature = 26;
temp = thermos.temperature; // should show 26 in Celsius but right now showing -3.333
console.log(temp);
我知道正确的解决方案是将 this.fahrenheit = temperatureInCelcius;
更改为 this.fahrenheit = (celsius * 9.0) / 5 + 32;
但是我不明白为什么。我被告知我的代码缺少转换。
我的问题是:
- 为什么需要将华氏度转换为摄氏度?
- 这一行到底发生了什么?
thermos.Temperature = 26;
我的理解是,当编译器看到该行时,它会在构造函数内调用该行
set temperature (temperatureInCelcius){
this.fahrenheit = temperatureInCelcius;
}
,然后将 26 放入参数 (temperingInCelcius)
中,然后将 this.fahrenheit
的属性值设置为 26。
只是想要一些解释,因为感觉好像我遗漏了一些东西。非常感谢您的帮助! <3
The Goal: Use the class keyword to create a Thermostat class. The constructor accepts a Fahrenheit temperature. In the class, create a getter to obtain the temperature in Celsius and a setter to set the temperature in Celsius.
Here's my code so far:
class Thermostat {
constructor(fahrenheit){
this.fahrenheit = fahrenheit;
}
get temperature(){
const inCelcius = 5/9 * (this.fahrenheit - 32) ;
return inCelcius;
}
set temperature (temperatureInCelcius){
this.fahrenheit = temperatureInCelcius;
}
}
const thermos = new Thermostat(76); // Setting in Fahrenheit scale
let temp = thermos.temperature; // should show 24.44 in Celsius
console.log(temp);
thermos.temperature = 26;
temp = thermos.temperature; // should show 26 in Celsius but right now showing -3.333
console.log(temp);
I know the correct solution is to change this.fahrenheit = temperatureInCelcius;
into this.fahrenheit = (celsius * 9.0) / 5 + 32;
But I don’t understand why. I've been told that my code is missing a conversion.
My questions are:
- Why is there a need to convert Fahrenheit into celsius?
- What exactly happens in this line?
thermos.temperature = 26;
My understanding is that when the compiler sees that line, it invokes this line inside the constructor
set temperature (temperatureInCelcius){
this.fahrenheit = temperatureInCelcius;
}
and then put 26 into the argument (temperatureInCelcius)
, then set the property value of this.fahrenheit
to 26.
Just want some explanation cause it feels like I am missing something. Would greatly appreciate your help! <3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您执行
temp = Thermos.Temperature;
时,会调用getTemperature()
并为thermos.Temperature = 26;
设置温度()
被调用。When you do
temp = thermos.temperature;
,get temperature()
is called and forthermos.temperature = 26;
set temperature()
is called.