Part 3
1. Use getters and setters to Control Access to an Object 🔖
-
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.
// Use the class keyword to create a Thermostat class. The constructor accepts a Fahrenheit temperature.
// Now create a getter and a setter in the class, to obtain 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.
// Note: When you implement this, you will track the temperature inside the class in one scale, either Fahrenheit or Celsius.
class Thermostat {
constructor(fahrenheit) {
this.fahrenheit = fahrenheit;
}
get temperature() {
return (5 / 9) * (this.fahrenheit - 32);
}
set temperature(celsius) {
this.fahrenheit = (celsius * 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
2. Create a Module Script
- ES6 introduced a way to easily share code among JavaScript files.
- This involves exporting parts of a file for use in one or more other files, and importing the parts you need, where you need them.
- In order to take advantage of this functionality, you need to create a script in your HTML document with a type of module
<html>
<body>
<!-- Only change code below this line -->
<script type="module" src="index.js"></script>
<!-- Only change code above this line -->
</body>
</html>
3. Use export to Share a Code Block
- Imagine a file called math_functions.js that contains several functions related to mathematical operations. One of them is stored in a variable, add, that takes in two numbers and returns their sum. You want to use this function in several different JavaScript files. In order to share it with these other files, you first need to export it.
const add = (x, y) => {
return x + y;
}
export { add };
4. Reuse JavaScript Code Using import
import
allows you to choose which parts of a file or module to load.
import { add } from './math_functions.js';
import { add, subtract } from './math_functions.js';
5. Use * to Import Everything from a File
- Suppose you have a file and you wish to import all of its contents into the current file
- The above import statement will create an object called
myMathModule
. - The object will contain all of the exports from math_functions.js in it, so you can access the functions like you would any other object property.
import * as myMathModule from "./math_functions.js";
myMathModule.add(2,3);
myMathModule.subtract(5,3);
6. Create an Export Fallback with export default
- In the
export
lesson, you learned about the syntax referred to as a named export. This allowed you to make multiple functions and variables available for use in other files. - There is another
export
syntax known as export default
. Usually you will use this syntax if only one value is being exported from a file. It is also used to create a fallback value for a file or module. - Since export default is used to declare a fallback value for a module or file, you can only have one value be a default export in each module or file.
- You cannot use export default with var, let, or const
// named function
export default function add(x, y) {
return x + y;
}
// anonymous function
export default function(x, y) {
return x + y;
}
7. Import a Default Export
- To import a default export, you need to use a different import syntax.
- In the following example, add is the default export of the math_functions.js file.
- The syntax differs in one key place. The imported value, add, is not surrounded by curly braces ({}). add here is simply a variable name for whatever the default export of the math_functions.js file is.
- You can use any name here when importing a default.
import add from "./math_functions.js";
8. Create a JavaScript Promise
- Promise is a constructor function, so you need to use the new keyword to create one.
- It takes a function, as its argument, with two parameters -
resolve
andreject
, which are methods used to determine the outcome of the promise. The syntax looks like this:
const myPromise = new Promise((resolve, reject) => {
});
const makeServerRequest = new Promise((resolve, reject) => {})
9. Complete a Promise with resolve and reject
- A promise has three states:
pending, fulfilled, and rejected
. - The promise you created in the last challenge is forever stuck in the
pending
state because you did not add a way to complete the promise. - The
resolve
andreject
parameters given to the promise argument are used to do this. resolve
is used when you want your promise to succeedreject
is used when you want it to fail.
const myPromise = new Promise((resolve, reject) => {
if(condition here) {
resolve("Promise was fulfilled");
} else {
reject("Promise was rejected");
}
});
- The example above uses strings for the argument of these functions, but it can really be anything. Often, it might be an object, that you would use data from, to put on your website or elsewhere.
const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer represents a response from a server
let responseFromServer;
if(responseFromServer) {
resolve("We got the data")
} else {
reject("Data not received")
}
});
10. Handle a Fulfilled Promise with then
- Promises are most useful when you have a process that takes an unknown amount of time in your code (i.e. something asynchronous), often a server request.
- When you make a server request it takes some amount of time, and after it completes you usually want to do something with the response from the server.
- This can be achieved by using the
then
method. The then method is executed immediately after your promise is fulfilled with resolve.
// result comes from the argument given to the resolve method.
myPromise.then(result => {
// do something with the result.
});
- Example
const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer is set to true to represent a successful response from a server
let responseFromServer = true;
if(responseFromServer) {
resolve("We got the data");
makeServerRequest.then(result =>{
console.log(result)
})
} else {
reject("Data not received");
}
});
11. Handle a Rejected Promise with catch
catch
is the method used when your promise has been rejected.- It is executed immediately after a promise’s reject method is called.
myPromise.catch(error => {
// do something with the error.
});
- Example
const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer is set to false to represent an unsuccessful response from a server
let responseFromServer = false;
if(responseFromServer) {
resolve("We got the data");
} else {
reject("Data not received");
makeServerRequest.catch(error => {
console.log(error);
})
}
});
makeServerRequest.then(result => {
console.log(result);
});
The quote today on freeCodeCamp is from Bruce Lee.