ES6: Use getters and setters to Control Access to an Object
ES6: Use getters and setters to Control Access to an Object
function makeClass() {
"use strict";
/* Alter code below this line */
class Thermostat {
constructor(temperature) {
this._temperature = temperature * 9.0 / 5 + 32 ;
}
get temperature() {
return this._temperature * 9.0 / 5 + 32;
}
set temperature(newTemperature) {
this.temperature = newTemperature * 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
thermos.temperature = 26;
temp = thermos.temperature; // 26 in C
>>>
Maximum call stack size exceeded
Maximum call stack size exceeded
Maximum call stack size exceeded
You need to rename your this.temperature to a different property name than the the getter/setter. That is causing a conflict with the getter/setter of the same name. You can use the still use temperature as a parameter for the constructor.
...
set temperature(newTemperature) {
this._temperature = newTemperature * 9.0 / 5 + 32;
}
...
留言
張貼留言