Hello,
So I have finally understood how constructors, getters and setters work but I have a couple questions still.
In the example they provided and challenge, both the setter and getter use the same property name (‘temperature’ and ‘writer’). So say we want to update the author, do we simply make the instance of the class with the parameter (‘writer’) equal our new desired author like below?
const novel = new Book('anonymous');
**novel.writer = 'newAuthor'**
If so, wouldnt it be better to name one parameter ‘updatedWriter’? (**novel.updatedWriter = 'newAuthor'**)
or do they have to have the same parameter name and if so, why?
Also, I don’t get the point of the getter if its simply returning the value we passed in from the instance. In the challenge it converts the value into Celsius so I see why its helpful there. But what does the setter do here? The equation is simply for Converting Celsius into Fahrenheit but doesnt actually pass in Celcius, it just states Celcius.
I don’t understand how they’re using this.temperature
. For the getter I understand they’re passing in the value 76 from the instance. But for the setter, which of the below are they staing?
76 = (celsius * 9.0) / 5 + 32;
OR
this.temperature = (celsius * 9.0) / 5 + 32;
where this.temperature refers to the variable, not its value so that the variable now has the value after the operator.
Thank you
**Your code so far**
class Thermostat {
constructor(fahrenheit) {
this.fahrenheit = fahrenheit;
}
get temperature() {
return (5 / 9) * (this.fahrenheit - 32);
}
set temperature(celsius) {
this.fahrenheit = (celsius * 9.0) / 5 + 32;
}
}
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
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36 Edg/94.0.992.50
Challenge: Use getters and setters to Control Access to an Object
Link to the challenge: