I tried to work with the new log of get/setter but i still don't really get it :Use getters and setters to Control Access to an Object

Tell us what’s happening:
The idea is here to 1st create a tempratue Fahrenheit
and then multiply it with celsius
and end with the new result

Your code so far


// Only change code below this line
//makes the class Thermostat holding both Fahrenheit and Celsius
class Thermostat (_Fahrenheit _Celsius){
 //sets Fahrenheit to it's temprature
 //Getter functions are meant to simply return (get) the value of an object's private variable to the user without the user directly accessing the private variable.'
 //basicly this means Fahrenheit get returned and set to the new variable
this._Fahrenheit = (F - 32);
}
get Celsius(_Celsius){ //sets Celsius to its temprature
 return this.__Fahrenheit = _Celsius * _Fahrenheit ;
 //returns Fahrenheit and sets its new value to the new sum}
//setter sets the new value 
   set Celsius(thermos) {
   this._Celsius = thermos;
 }
}
// 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

Your browser information:

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

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

Link to the challenge:

I don’t know if that’s passing the exercise, but I’d give you another possible code:

class Thermostat{
constructor(fahrenheit){
this._fahrenheit = fahrenheit
}
get temperature(){ 
 return (this._fahrenheit - 32)*5/9
}
set temperature(thermos) {
   this._fahrenheit = thermos;
 }
}

I imagine this like so: there is a thermostat in your house. You read values in fahrenheit, but you want to get it in celsius.

When you set, again you’re setting it in fahrenheit.

To bond this to previous knowledge, you can take a look at this reply I’ve made


Another version, and this under the hints, it’s to always set in celsius. I like it more, though it seems a bit unreal for me, the real object will only have one scale, not 2.

Anyways, this is the other option:

class Thermostat {
  constructor(fahrenheit) {
    this._fahrenheit = fahrenheit;
  }
  
  get temperature() { //getting in celsius
    return (5 / 9) * (this._fahrenheit - 32);
  }
  
  set temperature(celsius) { //setting in celsius
    this._fahrenheit = (celsius * 9.0) / 5 + 32;
  }
}

You could think of this as methods of the new object. So you call a method this way:

object.method  //to get
object.method = value //to set
1 Like