Challenge - ES6: Use getters and setters to Control Access to an Object - Added solution and explanation of private variable naming convention (#24362)
* added explanation of private variable naming convention * Added "Note:" to the front of the explanation * Added solution * Moved "Note:" to it's own line and made it bold * fix: moved note block at the bottom
This commit is contained in:
@ -9,10 +9,12 @@ challengeType: 1
|
||||
You can obtain values from an object, and set a value of a property within an object.
|
||||
These are classically called <dfn>getters</dfn> and <dfn>setters</dfn>.
|
||||
Getter functions are meant to simply return (get) the value of an object's private variable to the user without the user directly accessing the private variable.
|
||||
Setter functions are meant to modify (set) the value of an object's private variable based on the value passed into the setter function. This change could involve calculations, or even overwriting the previous value completely.
|
||||
Setter functions are meant to modify (set) the value of an object's private variable based on the value passed into the setter function. This change could involve calculations, or even overwriting the previous value completely.<br><br>
|
||||
<blockquote>class Book {<br> constructor(author) {<br> this._author = author;<br> }<br> // getter<br> get writer(){<br> return this._author;<br> }<br> // setter<br> set writer(updatedAuthor){<br> this._author = updatedAuthor;<br> }<br>}<br>const lol = new Book('anonymous');<br>console.log(lol.writer); // anonymous<br>lol.writer = 'wut';<br>console.log(lol.writer); // wut</blockquote>
|
||||
Notice the syntax we are using to invoke the getter and setter - as if they are not even functions.
|
||||
Getters and setters are important, because they hide internal implementation details.
|
||||
<br><br>
|
||||
<strong>Note:</strong><br>It is a convention to precede the name of a private variable with an underscore (<code>_</code>). The practice itself does not make a variable private.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
@ -72,6 +74,27 @@ temp = thermos.temperature; // 26 in C
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
function makeClass() {
|
||||
"use strict";
|
||||
/* Alter code below this line */
|
||||
class Thermostat {
|
||||
constructor(fahrenheit) {
|
||||
this._tempInCelsius = 5/9 * (fahrenheit - 32);
|
||||
}
|
||||
get tempInCelsius(){
|
||||
return _tempInCelsius;
|
||||
}
|
||||
set tempInCelsius(newTemp){
|
||||
this._tempInCelsius = newTemp;
|
||||
}
|
||||
}
|
||||
/* 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
|
||||
```
|
||||
</section>
|
||||
|
Reference in New Issue
Block a user