Using getters and setters

Tell us what’s happening:
I dont really get the point of this exercise. i got the code right but I am not sure how it works and in which way it is helping me. Could someone be so kind and explain it to me ?

  **Your code so far**

// Only change code below this line
class Thermostat{
constructor (zahl) {
  this._zahl = zahl 
} get temperature () {
  return 5/9 * (this._zahl - 32)             
} set temperature (celsius) {
  this._zahl = celsius * 9.0 / 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
const test = new Thermostat ( 68)
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36

Challenge: Use getters and setters to Control Access to an Object

Link to the challenge:

In other languages (especially strictly OOP languages) and later versions of JS, there is the idea of having a “private” class member. You only want the class to have access to it directly and you want to control access. Maybe you want to limit the ranges of temperatures, for example the temp -300C doesn’t exist. There are a lot of things you can do. Maybe when they retrieve it you want to check which country they are in so know to return F or C and knows whether to use a decimal point or decimal comma or to always round it off in a certain way. In some computer languages you can call the class member “private” and no one can access it. But you can define setters and getters to set and retrieve the data. In the version of JS that this was written it was not possible to declare it “private” (I think in TS you can call it “private” and in the more recent JS, you substitute a “#” for the “_”), but there was the tradition of writing it with a preceding underscore to tell people “treat this as if it is private”. That is what you are doing here.

So, _zahl is an “unreachable” property on that class, but you can modify it and read it with your setter and getter.

Does that make sense?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.