为什么 es6 中的 setter 函数 return 是摄氏度值而不是华氏度值
Why does the setter function in es6 return a celsius value instead of a farenheit value
我的问题是关于函数 makeClass() 中的 setter 函数。
set temperature(celsius) {
this.farenheit = celsius * 9.0 / 5 + 32;
}
为什么代码使用 F=C*9.0/5+32 的计算公式,这是华氏度的公式,return 26 摄氏度而不是 26 华氏度,如以下部分所示makeClass() 函数之外的代码。
温度=thermos.temperature; // C
中的 26
以下是 freecodecamp 的练习,它是正确的,但由于上述原因我实际上不明白它是如何工作的。
function makeClass() {
"use strict";
/* Alter code below this line */
class Thermostat {
constructor(farenheit) {
this.farenheit = farenheit;
}
get temperature() {
return 5 / 9 * (this.farenheit - 32);
}
set temperature(celsius) {
this.farenheit = celsius * 9.0 / 5 + 32;
}
}
/* Alter code above this line */
return Thermostat;
}
const Thermostat = makeClass();
const thermos = new Thermostat(76); // setting in Fahrenheit scale
let temp = thermos.temperature; // 24.44 in C
console.log(temp)
thermos.temperature = 26;
temp = thermos.temperature; // 26 in C
console.log(temp)
构造函数希望您向它传递一个以华氏度为单位的值,并将该值存储为华氏度。
getter 被编程为 return 摄氏度值,因此由于该值先前以华氏度存储,因此必须将存储值转换为摄氏度。
setter 被编程为接受摄氏度的值,但将其存储在华氏度中,因此它必须将传递的值转换为华氏度。
我不知道为什么构造函数被编程为接受华氏度值,但 getter 和 setter 处理摄氏度。您必须询问此代码的设计者他们为什么这样做。我的猜测是它只是为了演示目的,向您展示如何让 getter/setter 自动为您处理单位转换。
26在setter函数中传入参数celsius并转换为华氏度结果在getter函数中传入this.farenheit并转换为摄氏度和returns 26 C 在函数外调用时。
我的问题是关于函数 makeClass() 中的 setter 函数。
set temperature(celsius) {
this.farenheit = celsius * 9.0 / 5 + 32;
}
为什么代码使用 F=C*9.0/5+32 的计算公式,这是华氏度的公式,return 26 摄氏度而不是 26 华氏度,如以下部分所示makeClass() 函数之外的代码。
温度=thermos.temperature; // C
中的 26
以下是 freecodecamp 的练习,它是正确的,但由于上述原因我实际上不明白它是如何工作的。
function makeClass() {
"use strict";
/* Alter code below this line */
class Thermostat {
constructor(farenheit) {
this.farenheit = farenheit;
}
get temperature() {
return 5 / 9 * (this.farenheit - 32);
}
set temperature(celsius) {
this.farenheit = celsius * 9.0 / 5 + 32;
}
}
/* Alter code above this line */
return Thermostat;
}
const Thermostat = makeClass();
const thermos = new Thermostat(76); // setting in Fahrenheit scale
let temp = thermos.temperature; // 24.44 in C
console.log(temp)
thermos.temperature = 26;
temp = thermos.temperature; // 26 in C
console.log(temp)
构造函数希望您向它传递一个以华氏度为单位的值,并将该值存储为华氏度。
getter 被编程为 return 摄氏度值,因此由于该值先前以华氏度存储,因此必须将存储值转换为摄氏度。
setter 被编程为接受摄氏度的值,但将其存储在华氏度中,因此它必须将传递的值转换为华氏度。
我不知道为什么构造函数被编程为接受华氏度值,但 getter 和 setter 处理摄氏度。您必须询问此代码的设计者他们为什么这样做。我的猜测是它只是为了演示目的,向您展示如何让 getter/setter 自动为您处理单位转换。
26在setter函数中传入参数celsius并转换为华氏度结果在getter函数中传入this.farenheit并转换为摄氏度和returns 26 C 在函数外调用时。