Getting error on execution

below is my code for the topic “Use getters and setters to control access to an object”. I am getting this error “Reference error: Fahrenheit is not defined” when i execute the code


// Only change code below this line
class Thermostat{
constructor(fahrenheit){
this._fahrenheit = fahrenheit;
}
get temperature()
{
return  (5/9) * (fahrenheit - 32);
}
set temperature(tempInCelsius)
{
this._fahrenheit=(tempInCelsius * 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 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36

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

Link to the challenge:

your error is saying fahrenheite is not defined means you have not defined that variable but your are using it because you have defined

_fahrenheit as variable not fahrenheit

In the constructor function, you have a variable fahrenheit that you use to set an object property named this._fahrenheit. Within the scope of that constructor, there is a variable named Fahrenheit, but it only exists within that function - no other function in that class can see it.

However, by setting that object property, you define a property in a shared context. Within the class, this refers to the newly constructed object that the constructor, getter and setter all share.

In your setter, you are using the context properly - but in the getter, you’re trying to get something from another functions scope.

Can u please write the exact code for that?

Look at these two functions. The set temperature one works because it it’s setting the property. The get temperature is likely not working, because it is not accessing that same property.

If you change the variable in that getter to the object property, what happens?

Do you understand why you do not have access to the identifier fahrenheit here?

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

Do you understand why you are using this._fahrenheit here?

set temperature(tempInCelsius)
{
this._fahrenheit=(tempInCelsius * 9.0) / 5 + 32;
}

As said, use the same property for the getter as you are using for the setter.

2 Likes

Thanks! The code worked after changing the variable name in get property to this._fahrenheit

1 Like