DEV Community 👩‍💻👨‍💻

Naveen Dinushka
Naveen Dinushka

Posted on

Getters/Setters to control access to an object (freecodecamp notes)

Below is an example of a JS Class

class Book {
  constructor(author) {
    this._author = author;
  // getter
  get writer() {
    return this._author;
  // setter
  set writer(updatedAuthor) {
    this._author = updatedAuthor;
const novel = new Book('anonymous');
novel.writer = 'newAuthor';
Enter fullscreen mode Exit fullscreen mode

So here's the exercise se the class keyword to create a Thermostat class. The constructor accepts a Fahrenheit temperature.

In the class, create a getter to obtain the temperature in Celsius and a setter to set the temperature in Celsius.

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

if you dive into the coding part without reading the question you will probably get it wrong, note that the question says 'obtain the temp in celcius' and 'set the temperature in celcius and with the equation they have given us we can do just that.

// Only change code below this line
class Thermostat{
    this._temp =temp;
  get temperature(){
    return 5/9 * (this._temp - 32)

  set temperature(C){
    this._temp=C * 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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

⭐️🎀 JavaScript Visualized: Promises & Async/Await

async await