ES6 - Use getters and setters to Control Access to an Object

Tell us what’s happening:
Although I double checked my syntax with w3 schools, and eventually caved to look at the solution- It appears my Thermostat class isn’t being recognized by the checker

Your code so far

// Only change code below this line
class Thermostat {
  constructor(temperature) {
    this.temperature = temperature
  }

  get temperature() {
    // Convert Farenheit to Celsius
    return 5/9 * (this.temperature - 32)
  }

  set temperature(temp) {
    // Convert Celsius to Farenheit
    this.temperature = (temp * 9.0) / 5 + 32
  }
}
console.log(Thermostat)
// 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/105.0.0.0 Safari/537.36

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

Link to the challenge:

  constructor(temperature) {
    this.temperature = temperature
  }

You give the class property the name of “temperature”. But that is also the name you give to the getter and setter functions.

  get temperature() {
    return 5/9 * (this.temperature - 32)
  }

So, in that getter, when it sees this.temperature, it calls the getter. That sees this.temperature so it calls the getter, which sees … turtles all the way down.

That is why when I put your solution in, I see this in the console:

RangeError: Maximum call stack size exceeded

Traditionally we give it a different name than the getter/setter. It’s common to prefix the “private” class property with an underscore, as “_temperature”, just to keep them separate and clear.

1 Like

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