Understanding getters and setters

Tell us what’s happening:
I’m hoping someone can explain why we must use this.fahrenheit instead of just fahrenheit within the get and set functions. After a lot of research I’m still not understanding the difference very well.

  **Your code so far**

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

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

set temperature(celsius) {
  return this.fahrenheit = (celsius * 9) / 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 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36

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

Link to the challenge:

this is what tells us where fahrenheit exists. It tells us that it is a property of the Thermostat instance.

If you look at the constructor you will see fahrenheit and this.fahrenheit. The simple fahrenheit is the argument variable that is passed into the constructor. It only exists and is accessible inside the constructor function, meaning that get and set can’t access it. That’s why the constructor copies it into the class-level this.fahrenheit, which all class methods have access to.

3 Likes

“this” refers to the object calling the function, telling it that it’s supposed to look in it’s local namespace for an attribute or value.

I think some programming language get along without using the keyword - it depends on how they handle attributes and local/global variables.
You not only do this for the attribut, but also if you call other methods.
There might be a method “increase_temperature(degree)” you’d call “this.temperature” to get the current value and then set the new one.

2 Likes

So the first thing to understand is what we get back when we do new Thermometer(...). A constructor function (and a class is simply a different way of defining a constructor function) does a few things with that new keyword.

  1. Creates a new blank generic Object.
  2. Uses the code in the function to initialize that object somehow.
  3. Wires that new object into the constructor’s “prototype chain”.

The important bit is, we’re getting an object back. So in the context of getters and setters, this refers to our new object, allowing us to read or create properties on that object.

1 Like

Things are much clearer now. Thank you all!

2 Likes

I’m glad we could help. Happy coding!

3 Likes

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