Files

58 lines
1.5 KiB
Markdown
Raw Normal View History

2018-10-12 15:37:13 -04:00
---
title: Use getters and setters to Control Access to an Object
---
# Use getters and setters to Control Access to an Object
2018-10-12 15:37:13 -04:00
---
## Problem Explanation
2018-10-12 15:37:13 -04:00
Getters and setters are critical parts of a class/object. They allow you to control their attributes from the outside. They will become more prominent when you get started with the Object-Oriented Programming unit (coming up!). For now, this exercise shows you how to manipulate them with ES6.
---
## Hints
### Hint 1
2018-10-12 15:37:13 -04:00
Create the class, Thermostat. You're going to put your constructor, getter, and setter in here.
### Hint 2
2018-10-12 15:37:13 -04:00
Give the constructor a parameter (which you can name anything you want). Set the parameter to an attribute of the same name. Remember, you are initially setting things in Fahrenheit temperature.
2018-10-12 15:37:13 -04:00
### Hint 3
2018-10-12 15:37:13 -04:00
Create a get method that converts the Fahrenheit attribute to Celsius. Use the formula given to you.
2018-10-12 15:37:13 -04:00
### Hint 4:
2018-10-12 15:37:13 -04:00
Create a set method of the same name as the get method. It should have a parameter that accepts celsius temperature. Convert it to fahrenheit, and set it to the attribute.
2018-10-12 15:37:13 -04:00
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
2018-10-12 15:37:13 -04:00
```javascript
function makeClass() {
"use strict";
/* Alter code below this line */
class Thermostat {
constructor(fahrenheit) {
this.fahrenheit = fahrenheit;
2018-10-12 15:37:13 -04:00
}
get temperature() {
return (5 / 9) * (this.fahrenheit - 32);
2018-10-12 15:37:13 -04:00
}
set temperature(celsius) {
this.fahrenheit = (celsius * 9.0) / 5 + 32;
2018-10-12 15:37:13 -04:00
}
}
2018-10-12 15:37:13 -04:00
/* Alter code above this line */
return Thermostat;
}
```
</details>