7 exciting new features of JavaScript

Foreword

A ECMAScript standard production process, including Stage 0 to Stage 4 five phases, each submitted to the next stage requires approval by TC39. This article describes the new features in Stage 3 or Stage 4 stages, which means that should soon support these features in browsers and other engines.

First, like private variables

One of the latest proposal is a method of adding private variables in the class. We will use the # symbol indicates the class private variables. This eliminates the need to use a closure to hide do not want to expose to the outside world of private variables

class Counter { #x = 0; #increment() { this.#x++; } onClick() { this.#increment(); } } const c = new Counter(); c.onClick(); // 正常 c.#increment(); // 报错

# Modified by the member variable or member function has become a private variable, if you attempt to access an external Class, exception will be thrown. Now, this feature can be used in the latest version of Chrome and Node.js in.

Second, an optional operator chain

You may come across such a situation: When you need to access several layers of nested inside the object properties, will get the infamous error Can not read property 'stop' of undefined, then you have to modify your code to handle to handle properties chain each possible undefined objects, such as:

let nestedProp = obj?.first?.second;

Obj.first or if obj is null / undefined, short circuit calculation expression will return directly undefined

Third, the union operator vacancy

We in the development process, often encounter such a scenario: If the variable is null, the default value is used, we are implemented as follows:

let c = a ? a : b // 方式1let c = a || b // 方式2

Both methods have significant drawbacks, which will cover all false values, such as (0, '', false), the input values ​​may be effective in some cases.

To solve this problem, it was proposed to create a "nullish" coalescing operator, represented by ??. With it, we just set the default value in the first term is null or undefined.

For example, the following code:

const x = null;const y = x ?? 500;console.log(y); // 500const n = 0const m = n ?? 9000;console.log(m) // 0

I was for many years engaged in the development of a web front-end programmers old, currently doing his resignation in customized web front-end private course, I spent a month earlier this year put together a 2019 study of the most suitable web front-end learning dry goods, from the most basic HTML + CSS + JS HTML5 project to combat learning materials are finishing, given to every small front-end partners, want to get my web front-end can be added to the exchange qun, six hundred [] + [ six hundred ten one hundred fifty-one] + [], direct download in the group, to study
the web front end have any problems (learning methods, learning efficiency, how employment) can ask me.

Four, BigInt

One on Math has been a very bad reason JS is not an accurate representation of a number greater than 2 ^ 53, which makes considerable digital processing becomes very difficult.

1234567890123456789 * 123;// -> 151851850485185200000 // 计算结果丢失精度

Fortunately, BigInt (large integer) is to solve this problem. You can use the same common digital operator on the BigInt, for example, +, -, /, *,% and the like.

Creating value BigInt type is also very simple, just add n to after the number. For example, 123 becomes 123n. The BigInt global method can also be used (value) conversion into a digital reference value or numeric string.

const aNumber = 111;const aBigInt = BigInt(aNumber);aBigInt === 111n // truetypeof aBigInt === 'bigint' // truetypeof 111 // "number"typeof 111n // "bigint"

Just add at the end of n numbers, you can calculate the correct Tarsus:

1234567890123456789n * 123n;// -> 151851850485185185047n

But there is a problem in most operations can not be BigInt and Number mixed. Compare Number and BigInt is possible, but can not add them up.

1n < 2// true1n + 2// Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions

Now, this feature can be used in the latest version of Chrome and Node.js in.

Five, static field

It allows the class has static fields, similar to most OOP languages. Static fields can be used in place of enumeration, it can also be used for private fields.

class Colors {  // public static 字段  static red = '#ff0000';  static green = '#00ff00';  // private static 字段  static #secretColor = '#f0f0f0';}font.color = Colors.red;font.color = Colors.#secretColor; // 出错

Now, this feature can be used in the latest version of Chrome and Node.js in.

六、Top-level await

async / await characteristics of ES2017 (ES8) only allows the use of keywords await the async function, await a new proposal is intended to allow the use of keywords in the content in the top layer, for example, simplify the process of dynamically loaded modules:

const strings = await import(`/i18n/${navigator.language}`);

This feature is very useful debugging asynchronous content in the browser console (such as fetch), without the need to package it into an asynchronous function.

7 exciting new features of JavaScript

 

Another usage scenario is that it can be used in the top asynchronously initialized ES module (such as database connection). When introduced into such an "asynchronous module," the system will wait for the module it is parsed, then the execution depends on its modules. This returns a handle asynchronous mode initialization initialization promise than the current and wait for it to be more easily resolved. A module does not know whether its dependencies asynchronously.

// db.mjsexport const connection = await createConnection();// server.mjsimport { connection } from './db.mjs';server.start();

In this example, no action is taken until the completion of connection db.mjs in server.mjs.

Now, this feature can be used in the latest version of Chrome.

Seven, WeakRef

In general, in JavaScript, reference to an object is strongly retained, which means that as long as the hold object references, it will not be garbage collected.

const ref = { x: 42, y: 51 };// 只要我们访问 ref 对象(或者任何其他引用指向该对象),这个对象就不会被垃圾回收

Currently in Javascript, WeakMap and WeakSet is the only way a weak reference objects: add objects as the key to WeakMap or WeakSet in, is not going to prevent it from being recycled garbage.

 

const wm = new WeakMap();{  const ref = {};  const metaData = 'foo';  wm.set(ref, metaData);  wm.get(ref);  // 返回 metaData}// 在这个块范围内,我们已经没有对 ref 对象的引用。// 因此,虽然它是 wm 中的键,我们仍然可以访问,但是它能够被垃圾回收。const ws = new WeakSet();ws.add(ref);ws.has(ref);// 返回 true

 

JavaScript is WeakMap not weak references in the true sense: in fact, as long as the key is still alive, it is a strong reference to its contents. WeakMap after the key is garbage, it was only a weak reference content.

WeakRef is a higher-level API, which provides real weak reference, Weakref instance has a method deref, which returns the original object referenced, if the original object has been collected, undefined object is returned

const cache = new Map();const setValue =  (key, obj) => {  cache.set(key, new WeakRef(obj));};const getValue = (key) => {  const ref = cache.get(key);  if (ref) {    return ref.deref();  }};// this will look for the value in the cache// and recalculate if it's missingconst fibonacciCached = (number) => {  const cached = getValue(number);  if (cached) return cached;  const sum = calculateFibonacci(number);  setValue(number, sum);  return sum;};

 



Guess you like

Origin www.cnblogs.com/Vay123/p/12098433.html