Understanding classes

Understanding classes:
Although I managed to pass this challenge, I do not understand the concept of these things :

  1. constructor
  2. this

Could somebody help me understand this ?

// Only change code below this line
class Thermostat{
  this._farenheit = farenheit;
get temperature(){
  return (5/9)*(this._farenheit - 32);
set temperature(celsius){
  this._farenheit = (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

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

Link to the challenge:

A constructor is a special method that runs when you create an instance of the class using the new keyword. It does initial work to setup the object.

this can get weird, but for the current context this refers to the current instance of the class.

If you

const myTherm = new Thermostat(72);

The constructor runs and 72 is set as the internal _farenheit variable. From our code, we would refer to this newly created thermostat as myTherm. The methods built into the class are referring to myTherm when they use this.


Now I get a clear picture about this. Thanks a lot for helping me out. :innocent:

1 Like

Iā€™m glad I could help. Happy coding!

1 Like

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