Codesmith programming: 7 exciting new features of JavaScript

Preface

An ECMAScript standard production process includes five stages from Stage 0 to Stage 4. Each stage is submitted to the next stage for approval by TC39. This article describes that these new features are in Stage 3 or Stage 4, which means that these features should be supported in browsers and other engines soon.

1. Private variables
of the class One of the latest proposals is to add private variables to the class. We will use the # symbol to denote the private variables of the class. This eliminates the need to use closures to hide private variables that you don't want to expose to the outside world

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

A member variable or member function modified by # becomes a private variable. If you try to access it outside the Class, an exception will be thrown. Now, this feature is available in the latest versions of Chrome and Node.js.

2. Optional chain operator
You may have encountered such a situation: when you need to access several layers of properties nested inside an object, you will get the notorious error Cannot read property'stop' of undefined, and then you have to modify it Your code handles every possible undefined object in the property chain, such as:

let nestedProp = obj?.first?.second;
如果obj或obj.first是null/undefined,表达式将会短路计算直接返回undefined

I am an old web front-end programmer who has been engaged in development for many years. Some time ago, I spent a month sorting out a web front-end learning dry product that is most suitable for learning. Various frameworks are organized and sent to every front-end small Partners, if you want to get it, you can add the following QQ group to get it for free.

Insert picture description here

Three, the space merge operator

In the development process, we often encounter such a scenario: if the variable is empty, the default value is used. This is how we achieved it:

let c = a? a: b // Method 1 let c = a || b // Method 2
These two methods have an obvious drawback, they will cover all false values, such as (0,'', false), These values ​​may be valid inputs in certain situations.

To solve this problem, someone proposed to create a "nullish" coalescing operator, denoted by ??. With it, we only set the default value when the first item 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

Four, BigInt

One of the reasons JS has always been bad on Math is that it cannot accurately represent numbers greater than 2^53, which makes it very difficult to deal with fairly large numbers.

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

Fortunately, BigInt (big integer) is to solve this problem. You can use the same operators as ordinary numbers on BigInt, such as +, -, /, *, %, etc.

Creating a value of type BigInt is also very simple, just add n after the number. For example, 123 becomes 123n. You can also use the global method BigInt(value) to convert, and the input parameter value is a number or a string of numbers.

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

As long as you add n to the end of the number, you can calculate the large number correctly:

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

But there is a problem. In most operations, BigInt and Number cannot be mixed. It is possible to compare Number and BigInt, but you cannot add them together.

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

Now, this feature is available in the latest versions of Chrome and Node.js.

Five, static field
It allows classes to have static fields, similar to most OOP languages. Static fields can be used instead of enumerations, and 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 is available in the latest versions of Chrome and Node.js.

6.
The async/await feature in Top-level await ES2017 (ES8) only allows the use of the await keyword in async functions. The new proposal aims to allow the use of the await keyword in the top-level content, for example, to simplify dynamic module loading process:

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

This feature is very useful for debugging asynchronous content (such as fetch) in the browser console without having to wrap it in an asynchronous function.
Insert picture description here
Another use case is that it can be used at the top level of an ES module that is initialized asynchronously (such as establishing a database connection). When importing such an "asynchronous module", the module system will wait for it to be resolved, and then execute the modules that depend on it. This way of handling asynchronous initialization is easier than currently returning an initialization promise and waiting for it to resolve. A module does not know whether its dependencies are asynchronous.

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

In this example, nothing will be performed until the connection is completed in server.mjs db.mjs.

This feature is now available in the latest version of Chrome.

Seven, WeakRef
Generally speaking, in JavaScript, the reference of the object is strongly reserved, which means that as long as the reference of the object is held, it will not be garbage collected.

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

Currently in Javascript, WeakMap and WeakSet are the only methods for weakly referencing objects: adding an object as a key to the WeakMap or WeakSet will not prevent it from being garbage collected.

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's WeakMap is not a weak reference in the true sense: in fact, as long as the key is still alive, it strongly references its content. WeakMap only weakly references its contents after the key is garbage collected.

WeakRef is a more advanced API that provides a real weak reference. Weakref instances have a method deref, which returns the referenced original object, and if the original object has been collected, it returns the undefined object.

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 blog.csdn.net/ZYDX18984003806/article/details/103701088