Constructor, getter, and setter

Tell us what’s happening:
How are the constructor, getter, and setter functions working together?
I thought I understood this problem because I solved it, but then I looked at the solutions.
How is my solution different from FreeCodeCamp’s solution?

Your code so far


function makeClass() {
  "use strict";
  /* Alter code below this line */
class Thermostat {
  constructor (temperature) {
    this.temperature = 5/9 * (temperature - 32);
  }
  get () {
return this.temperature;
  }
  set (updatedTemp) {
    this.temperature = updatedTemp;
  }
}
  /* 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

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object

The tests for this challenge are poorly written. Your getter and setter aren’t being used at all. thermos.temperature is accessing the temperature field of thermos directly. This is why “private” (not really) class fields usually have a _ before them, to discourage this kind of access.

1 Like

constructor(temperature) {
// your code is this.temperature = _something
this._something = temperature;
}
get temp() {
//your code is return this.temperature
return this._something;
}

set temp(something_new) {
//your code this.temperature = something_new
this._something = something_new;
}