提问人:theonerishi 提问时间:9/23/2023 最后编辑:Peter Mortensentheonerishi 更新时间:10/9/2023 访问量:76
修复了代码以创建由基础字段 [duplicate] 支持的 getter/setter 属性
Fix code to create a getter/setter property backed by an underlying field [duplicate]
问:
从https://github.com/freeCodeCamp/freeCodeCamp/blob/139eecad25760621d42e482e34b6b57c980b6094/curriculum/challenges/english/02-javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object.md#--instructions--
使用关键字创建类。接受华氏温度。
class
Thermostat
constructor
在类中,创建 a 以获得以摄氏度为单位的温度,创建 a 以摄氏度为单位设置温度。
getter
setter
请记住,和 ,其中是以华氏度为单位的温度值,是以摄氏度为单位的相同温度值。
C = 5/9 * (F - 32)
F = C * 9.0 / 5 + 32
F
C
注意:实现此功能时,您将在一个刻度(华氏度或摄氏度)中跟踪类内的温度。
这就是吸气剂和二传手的力量。您正在为另一个用户创建一个 API,无论您跟踪哪个用户,该用户都可以获得正确的结果。
换言之,您正在从用户那里抽象出实现细节。
// 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
怎么了?
答:
1赞
Konrad
9/23/2023
#1
您必须创建一个属性,否则,您在使用this.temperature
)
// Only change code below this line
class Thermostat {
_temperature = 0
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
console.log(temp)
您可以使用以下方法创建私有属性#
// Only change code below this line
class Thermostat {
#temperature = 0
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
console.log(temp)
评论