1. Privatization of variables

We define the class for better abstraction and reuse, but there are some variables in the class that we do not want the outside world to modify or use directly. We prefer it to be privatized, so we can add “#” before these variables to achieve the purpose of privatization.

# Variable name = variable valueCopy the code

Example:

Class Person {#hobby = 'I am a private hobby'; // Private attributes cannot be changed directly outside or use name = 'I am a common attribute name'; SetHobby = function (hobby) {setHobby = function (hobby) {this.#hobby = hobby; } getHobby = function () {return this.#hobby; } } const p = new Person(); console.log(p); // Result: Person {name: "I have a shared property name", #hobby:" I have a private property name", setHobby: ƒ, getHobby: ƒ} // If P. #hobby is used Result: Uncaught SyntaxError: Private field '#hobby' must be declared in an enclosing class console.log(p.hobby); // Result: undefined (because there is no hobby property on p) console.log(p.name); // result: I am a common attribute name console.log(p.gethobby ()); // Result: I am a private property hobby p.thobby (' new property value '); console.log(p.getHobby()); // Result: new property valueCopy the code

2.Promise.allSettled()

Promise had both the All and race methods before. Race executes multiple requests concurrently, taking an array of requests and returning the success of the first request. All also executes multiple requests concurrently. The parameter is a reject array and returns all requests. However, if there is a reject, all requests are caught. The new allSettled method is designed to solve the problem of not getting the results of another request when a request is settled in error in the All method. AllSettled will always collect the results of all requests, right or wrong. Example:

Const p1 = new Promise((resolve, reject) => {reject(' error '); }) const p2 = new Promise((resolve, reject) => {resolve(' second right '); }) const p3 = new Promise((resolve, reject) => {resolve(' resolve, reject '); }) // race returns only the result of the first response, right or wrong. Promise.race([P1, p2, p3]).then(res => {console.log('race request succeeded: ', res); }). Catch (err => {console.log('race request failed: ', err); All ([p2, p1, p3]). Then (res => {console.log('all request succeeded: ', res); }). Catch (err => {console.log('all failed: ', err); }) // allSettled collects all response results and returns, right or wrong. Promise.allsettled ([P1, P2, p3]). Then (res => {console.log("allSettled: ", res); })Copy the code

Results:

3.BigInt Basic data type

Data of type Js Number represents 16 significant bits. If the Number exceeds 16 bits, the accuracy will be lost. ES2020 adds a new base data type, BigInt, to remedy this problem. The diagram below:



Two ways to use BigInt data :(1)Add n to the integer;(2)With BigInt, arguments should be integers ending in n, otherwise more than 16 bits lose precision

Example:

const num = 12345678901234567; Console. log(num) // Result: 12345678901234568 (lost precision) console.log(typeof num) // Result: number const btNum1 = 12345678901234567n; Log (btNum1) // Result: 12345678901234567n console.log(typeof btNum1) // Result: bigint const btNum2 = BigInt(12345678901234567n); Log (btNum2) // Result: 12345678901234567n console.log(typeof btNum2) // Result: BigIntCopy the code

4. Null value merge operator

(1) Symbol:?? Rule: ** The result is value 2 if and only if value 1 is null or undefined. (4) using scene: * * * * in the development of our common short-circuit operator | | is a variable assignment, in order to prevent some false operations on data or display some bad influence. For example: const type = data | | ‘–‘; When data is false, type is’ – ‘, but sometimes we want values like 0 or false. This simplification is not possible, so we have to use if or other methods instead. Null-value merge operators are designed to solve this problem. Example:

function exp4Fun(data) { const type1 = data || '--'; const type2 = data ?? '-'; Console. log(' result of passing ${data}, type1=${type1}; type2=${type2}`); } exp4Fun(null); exp4Fun(undefined); exp4Fun(false); exp4Fun(0); exp4Fun('');Copy the code

Results:

5. Optional chain operators

(1) Symbol:? . (2) ** function: ** in deep object nesting, use? If null or undefined was encountered before, undefined will be returned without error. (3) ** Usage scenarios: ** When accessing properties of deeply nested objects, we must determine whether each layer of properties has been declared and assigned to the layer we want to use through expressions. If the level is deep, the judgment expression is long. If the properties of a layer are undetermined and happen to be null or undefined, the program crashes. The optional chain operation is used to solve this problem.

const country = { province: { city: { town: { village: }}}} // In order to avoid null or undefined of a certain layer in time, we have to make a judgment on each layer before using the village under exp5Obj to prevent errors. Although using the circuit breaker operation simplifies a lot, it is still not friendly. const village1 = country && country.province && country.province.city && country.province.city.town && country.province.city.town.village; // If a layer is null or undefined, undefined is returned, const village2 = country? .province? .city? .town? .village;Copy the code

Results:

6. GlobalThis global object

For example, the global object can be obtained through window, self and frames in the browser. In Web Workers, there is no window to use self, and in Node, there is only global. This results in different syntax for JS code to work in multiple environments. The result is a unified globalThis.

Previously, to get a global object across platforms, the code might look like this:

const country = { province: { city: { town: { village: }}}} // In order to avoid null or undefined of a certain layer in time, we have to make a judgment on each layer before using the village under exp5Obj to prevent errors. Although using the circuit breaker operation simplifies a lot, it is still not friendly. const village1 = country && country.province && country.province.city && country.province.city.town && country.province.city.town.village; // If a layer is null or undefined, undefined is returned, const village2 = country? .province? .city? .town? .village;Copy the code

With globalThis:

If (typeof Globalthis.setTimeout! == 'function') {// setTimeout() is not available in this environment}Copy the code

7. Dynamic import

Do not import resources when they are not in use. Import resources when they are in use.

math.js

 const add = (num1, num2) => num1 + num2;
 export {
     add
 };
Copy the code

Use the local dynamic introduction

const exp7Btn = document.querySelector('#btn'); Exp7btn.onclick = async () => {// const add = await import('./math.js'); add(1, 2); }Copy the code

If you can help 👍+ attention, we learn front-end ~~

Also see here: New ES2020 features Do you know?