Stuck on: Use getters and setters to Control Access to an Object

Tell us what’s happening:
Can someone please explain to me where I am going wrong. I followed the example given in this lesson, and when I run the code it tells me I need to define a getter and setter, but I used get() and set(), so that would define a getter and a setter no? I looked at the solution, and re-tried to complete the challenge myself a few days later, and am still just as confused with the entire challenge.

  **Your code so far**

// Only change code below this line
class Thermostat {
constructor(temp) {
  this.temp = temp;
}
//getter
get fahrenheit() {
 return (5 / 9) * (this.temp - 32);
}

//setter 

set fahrenheit(celsius) {
 this.temp = (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
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.109 Safari/537.36

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

Link to the challenge:

The name of your getter and setter should match name of the property that will be accessed outside the class.

Notice in the example:

class Book {
  constructor(author) {
    this._author = author;
  }

  get writer() {
    return this._author;
  }

  set writer(updatedAuthor) {
    this._author = updatedAuthor;
  }
}
const novel = new Book('anonymous');
console.log(novel.writer);
// ...

Notice that the class has getter and setters for “writer” and then that is how the code outside the class uses it, as novel.writer. It looks like it is accessing a property but really, behind the scenes JS is calling the getter. In some languages you would call the getter as a function. In JS you treat it like a property and JS figures it out.

Also notice that there is the “secret” property of “_author” that it uses to store the value internally. In some languages you can make this truly invisible. In this version of JS we just have the convention of starting with an underscore to tell us that it is “private” to the class, even though technically it is not.

Really, your issues are naming. When I fix the names of your getters and setters and fix the name of your “private” property, your code passes for me.

Don’t feel bad, a lot of people get hung up on this challenge.

Thank you so much Kevin! That totally makes sense, I couldn’t figure out where I was going wrong, I even compared my code to the solution code offered in the guide, and I still didn’t understand it.

1 Like

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