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

I cant solve this challenge help!!!
Use class keyword to create a Thermostat class. The constructor accepts Fahrenheit temperature.

Now create getter and setter in the class, to obtain the temperature in Celsius scale.

Remember that C = 5/9 * (F - 32) and F = C * 9.0 / 5 + 32, where F is the value of temperature in Fahrenheit scale, and C is the value of the same temperature in Celsius scale

Note

When you implement this, you would be tracking the temperature inside the class in one scale - either Fahrenheit or Celsius.

This is the power of getter or setter - you are creating an API for another user, who would get the correct result, no matter which one you track.

In other words, you are abstracting implementation details from the consumer.

function makeClass() {
“use strict”;
/* Alter code below this line */

/* Alter code above this line */
return Thermostat;
}
const Thermostat = makeClass();
const thermos = new Thermostat(76); // setting in Fahrenheit scale
let temp = thermos.temperature; // 24.44 in C
thermos.temperature = 26;
temp = thermos.temperature; // 26 in C

1 Like

Read this article to know more about getters and setters and try to solve the challenge.

https://javascriptplayground.com/es5-getters-setters/

1 Like

Thanks alot, it was really helpful

Why was I able to bypass the test with just,

function makeClass() {
“use strict”;
/* Alter code below this line /
class Thermostat {
constructor(Fahrenheit){
this.Thermostat=temp;
}
}
/
Alter code above this line */
return Thermostat;
}
const Thermostat = makeClass();
const thermos = new Thermostat(76); // setting in Fahrenheit scale
let temp = thermos.temperature; // 24.44 in C
thermos.temperature = 26;
temp = thermos.temperature; // 26 in C

1 Like

Hi there,
I may be wrong, based on my understanding the getters and setters should be inside the constructor function. Otherwise the keyword this will not be defined. Try this.

I was able to pass this challenge and wanted to see if other people agree that the way the example is written was incorrect.

Hi there!
@newtonmathias try defining what exactly you cant solve here, where did you stuck.

btw you well pass the test only by writing a simple setter and a constructor even without applying formulas. Tests are checking only for creation of constructor inside an instantiatable (does the word exist?) class :slight_smile:
here is my solution which I wrote with Quokka plugin in VScode - very hendy in terms of inline output and fast feedback :slight_smile:
Hope it helps to understand

 class Thermostat{
    constructor(temperature) {
      this._temperature = temperature;
    }
  
    get temperature() {
        return 5/9 * (this._temperature-32); // return in C
    }

    set temperature(tempCels) {
        this._temperature = tempCels * 9 / 5 + 32; // convert C -> F
    }
  }

const thermos = new Thermostat(76); // setting in Fahrenheit scale
let temp = thermos.temperature; // 24.44 in C
thermos.temperature = 26;
temp = thermos.temperature; // 26 in C
8 Likes

Just a question, what does set and get do? I didn’t understand the lesson.

In javascript setters and getters are methods in a class that allow you to treat it’s values like a regular object.

so something like

class SomeClass {
  constructor(initialValue) {
      this.val = initialValue
  }

  get value() {
      return this.val
  }

  set value(value) {
      this.val = value
   }
}

Then later you can use it like a regular object

const newInstance = new SomeClass('my initial value')

console.log(newInstance.value) // 'my initial value'
newInstance.value = 'new value'
console.log(newInstance.value)  // 'new value'

If it was regular object, it would look like this

const SomeClass = {
   value: 'my initial value'
}

const newInstance = {...SomeClass} // clone as new object

console.log(newInstance.value) // 'my initial value'
newInstance.value = 'new value'
console.log(newInstance.value)  // 'new value'
6 Likes

Thanks for this, that explanation was much clearer than what I found with the exercise!

This was SO much more helpful than the explanation given with the exercise itself. THANK YOU!

I also found that reading the following resource on constructors was a huge help too:

https://css-tricks.com/understanding-javascript-constructors/

Thank you so much. I really wished if the lesson has this explaination, Freecodecamp’s new lessons are really bad.

Just an additional question, can you please explain set and get’s syntax?

I really don’t get it. I mean, why you made get something() or why you made set something(something1)

I mean what you do with the property on set like you made “val” one, and what is “value” you made on both?

1 Like

I’m looking into submitting a pull request for answers people find useful. You can’t really fault FCC devs. They have to code the site on their free time. Whereas I have more time to troubleshoot people’s questions.

Considering even commercial software has issues with documentation, I feel they’re doing great imho. And that’s why this forum is helpful.

I think I may have confused you because I made a critical mistake, which I just went back to fix. The example should have looked like this

class SomeClass {
  constructor() {
      this.value = 'my initial value'
  }

  get value() {
      return this.value
  }

  set value(val) {
      this.value = val
   }
}

The reason we use get and set is so that we can work with a class like a regular object. Variables inside a class are private data, and only the class’ methods can access that data.

So internally the js engine knows that

  • when you try to set the property to a value, it will run set someFunc.
  • when you try to get the value of the property, it will run get someFunc.

This allows you to be in absolute control of how to set the data, and what data gets returned to the caller.

For instance, suppose I have a class to create a bank account. In order to make accounting easier, the specs require us to save the total as one cent denominations, but can only accept dollars.

Why? Because sometimes specs are specs and the client is boss. :confused: lol

For the sake of this example, let’s assume you cannot set the beginning total in the contructor.

class BankAccount {
  constructor() {
      this.total = 0
  }

  get total() {
    // get the total in dollars
      return this.total / 100
  }

  set total(amt) {
  // convert amt to 1 cent denominations and deposit
      this.total = amt * 100
   }
}

Now when I create a new Bank account for someone, I can treat that specific property like it was an object literal.

// create a new account for Bob
const bobsAcct = new BankAccount()

// make sure bob's account starts at 0
// this "get"s the data
console.log(bobsAcct.total) // 0

// set his opening balance to $100
// this "set"s the data
bobsAcct.total = 100

// now let's see how much he has
console.log(bobsAcct.total) // 100

By using setters and getters, we were able to use the class like an object literal.

We also abstracted the dollar → penny conversion, so the user of the class doesn’t have to worry about that logic.

I think that’s what you were asking for. So if I misunderstood, let me know what to clarify.

6 Likes

Thank you so much. I think I got it right now.

You was really useful. Thank you a lot again for helping us with the lesson!

1 Like

Could someone explain why the underscore before temperature was necessary? Im assuming it’s just their check since underscoring doesnt actually do anything internally and is more of a common “make a property private” convention, at least in javascript.

Unlike other languages, javascript doesn’t have any real private data. We just fake it. This means that even if you made a method or variable private, anyone with access to the object could find a way to access it.

Before we had classes with the static method and such, the convention was to prefix a private method or variable with _ so that whoever called it knew it was private, and was not to be accessed directly.

1 Like

you can put only temperature without using this keyword because it is a parameter in the constructor function can’t you ??

1 Like

For thermos.temperature = 26 the function returns 26. Which part of the function is doing this? I would have though since the input 26 is Celsius the function would use the set code to return the temperature in Fahrenheit.

In fact I don’t see any part of the code which would simply return the input of temperature as it is. Can you please elaborate?

2 Likes

https://www.youtube.com/watch?v=bl98dm7vJt0 Check this video, getters and setters are explained very clearly.

I tried this - none of this works.

Hi, if someone could explain a point about this exercise.
I build my resolutions step by step, then I try checking(run) every step.
I left the temperature calc for the last because I don’t understand where I should put this part: “Remember that C = 5/9 * (F - 32) and F = C * 9.0 / 5 + 32, where F is the value of temperature in Fahrenheit scale, and C is the value of the same temperature in Celsius scale”
Then when I tried to validate my code and just passed, without any temperature calc.
There’s something wrong with the validations tests? Where should be this calculation?
That was my code:

1 Like