Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analyze the new features of JavaScript

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "analyzing the new features of JavaScript". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Private variables of the class

One of the latest proposals is a method to add private variables to a class. We will use the # symbol to represent the private variable of the class. This eliminates the need to use closures to hide private variables that you do not want to expose to the outside world.

Class Counter {# x = 0; # increment () {this.#x++;} onClick () {this.#increment ();}} const c = new Counter (); c.onClick (); / / normal c.#increment (); / / error report

Member variables or member functions modified by # become private variables, and if you try to access them outside of Class, an exception will be thrown. This feature is now available in the latest versions of Chrome and Node.js.

Optional chain operator

You may have come across a situation where when you need to access properties nested in several layers of an object, you get the infamous error Cannot read property 'stop' of undefined, and then you have to modify your code to handle every possible undefined object in the property chain, such as:

EdProp = obj & & obj.first & & obj.first.second

Before accessing obj.first.second, the values of obj and obj.first are confirmed to be non-null (and not undefined). The goal is to prevent errors, which may occur if you simply access obj.first.second without verifying obj and obj.first.

With optional chained calls, you can do the same thing simply by writing:

Let nestedProp = obj?.first?.second

If obj or obj.first is null/undefined, the expression will be short-circuited and will directly return undefined.

III. Vacancy merging operator

In the process of development, we often encounter such a scenario: if the variable is null, the default value is used, and this is how we implement it:

Let c = a? A: B / / Mode 1 let c = a | | b / / Mode 2

The obvious drawback of both approaches is that it overrides all false values, such as (0,', false), which may be valid inputs in some cases.

To solve this problem, it has been proposed to create a "nullish" merge operator, using? It means. With it, we only set the default value when the first item is null or undefined.

Let c = a? B; / / equivalent to let c = a! = = undefined & & a! = = null? A: b

For example, there is the following code:

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

IV. BigInt

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

1234567890123456789 * 123; / / > 151851850485185200000 / / the accuracy of the calculation result is lost

Fortunately, BigInt (large integers) is here to solve this problem. You can use the same operators as ordinary numbers on BigInt, such as +, -, /, *,%, and so on.

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

Const aNumber = 111; const aBigInt = BigInt (aNumber); aBigInt = = 111n / / true typeof aBigInt = = 'bigint' / / true typeof 111n / / "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

One problem, however, is that in most operations, you cannot mix BigInt with Number. It's OK to compare Number and BigInt, but you can't add them up.

1n

< 2 // true 1n + 2 // Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions 现在,此特性可在最新版本的 Chrome 和 Node.js中使用。 五、static 字段 它允许类拥有静态字段,类似于大多数OOP语言。静态字段可以用来代替枚举,也可以用于私有字段。 class Colors { // public static 字段 static red = '#ff0000'; static green = '#00ff00'; // private static 字段 static #secretColor = '#f0f0f0'; } font.color = Colors.red; font.color = Colors.#secretColor; // 出错 现在,此特性可在最新版本的 Chrome 和 Node.js中使用。 六、Top-level await ES2017(ES8)中的 async/await 特性仅仅允许在 async 函数内使用 await 关键字,新的提案旨在允许 await 关键字在顶层内容中的使用,例如可以简化动态模块加载的过程: const strings = await import(`/i18n/${navigator.language}`); 这个特性在浏览器控制台中调试异步内容(如 fetch)非常有用,而无需将其包装到异步函数中。 另一个使用场景是,可以在以异步方式初始化的 ES 模块的顶层使用它(比如建立数据库连接)。当导入这样的"异步模块"时,模块系统将等待它被解析,然后再执行依赖它的模块。这种处理异步初始化方式比当前返回一个初始化promise并等待它解决来得更容易。一个模块不知道它的依赖是否异步。 // db.mjs export const connection = await createConnection();// server.mjs import { connection } from './db.mjs'; server.start(); 在此示例中,在server.mjs中完成连接之前不会执行任何操作db.mjs。 现在,此特性可在最新版本的 Chrome中使用。 七、WeakRef 一般来说,在 JavaScript 中,对象的引用是强保留的,这意味着只要持有对象的引用,它就不会被垃圾回收。 const ref = { x: 42, y: 51 }; // 只要我们访问 ref 对象(或者任何其他引用指向该对象),这个对象就不会被垃圾回收 目前在 Javascript 中,WeakMap 和 WeakSet 是弱引用对象的唯一方法:将对象作为键添加到 WeakMap 或 WeakSet 中,是不会阻止它被垃圾回收的。 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 的 WeakMap 并不是真正意义上的弱引用:实际上,只要键仍然存活,它就强引用其内容。WeakMap 仅在键被垃圾回收之后,才弱引用它的内容。 WeakRef 是一个更高级的 API,它提供了真正的弱引用,Weakref 实例具有一个方法 deref,该方法返回被引用的原始对象,如果原始对象已被收集,则返回undefined对象。 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 missing const fibonacciCached = (number) = > {const cached = getValue (number); if (cached) return cached; const sum = calculateFibonacci (number); setValue (number, sum); return sum;}

All in all, references to objects in JavaScript are strong references, and WeakMap and WeakSet can provide some of the weak references. If you want to implement a real weak reference in JavaScript, you can do it by using WeakRef and Finalizer together.

This is the end of "analyzing the New Features of JavaScript". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report