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

What are the features of the new version of ECMAScript

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "what are the functions of the new version of ECMAScript". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "what are the functions of the new version of ECMAScript?"

The method of replaceAll string

This method has been in place for a long time, and the existing replace method should have been effective a long time ago. As you may not know, the current replace method from the String object only affects the first match found, unless, of course, you use a regular expression instead of a simple string as the first parameter.

This is not a great progress, but more of a supplement, but it is still commendable.

Const str = "The brown fox is reallybrown"; / / Instead of doing this... Const newStr = str.replace (/ brown/g, "White"); / / You'll be able to do this... Const newStr = str.replaceAll ("brown", "White")

Privacy modifiers for methods and accessors

We haven't heard of any progress in privacy (the proposal is still in the third phase), but as a future attempt, we will be able to set visibility to methods and accessors. In this case, "visibility" means to make them personal, which means that we finally have a basic way to protect our code and begin to slowly move towards more OOP-oriented coding (not that there is anything wrong with our current functional approach).

ClassPerson {constructor (name, birhdate, city) {this.name= name; this.birthdate= birthdate; this.city= age } get # Age () {/ / return actualage} # myPrivateMethod () {console.log ("You can't use this from outside of this class")}}

In essence, you are using the # character to privatize a method or accessor. This character will also be part of the name, so if you want to use the method mentioned above, you can simply use this.#Age or this.#myPrivateMethod ().

In both cases, if you try to use them from outside a class or even from an extended class, an exception will occur (wait until you have a protected method).

Terminator and weak reference ‍

These two interesting tools can help deal with memory usage problems and manage garbage collection. However, unless you need to pay special attention to the use of memory, you don't need to use these two tools.

Note that the following two features relate to how the garbage collector works, but the installation is enabled for only one runtime. This means that writing business logic that relies on non-standard installations is likely to produce unexpected results. Even if you have these tools, be aware of your goals before using them.

(1) weak reference

Before I introduce weak references, let me quickly introduce strong references so that you can understand the advantages of weak references. A strong reference is essentially a pointer to a target. In JavaScript, this is just a variable to which you have assigned the target. For example:

ClassPerson {constructor (first_name, last_name) {this.first_name = first_name; this.last_name = last_name;}} let myP = new Person ("Fernando", "Doglio")

In the above, myP is a valid strong reference until it no longer exists. Once all strong references to an object are eliminated, the garbage collector is free to destroy the object and free up its memory for other things. That is, in some cases, such as the one below, a strong reference may lock a target so that it can never be released.

ClassPerson {constructor (first_name, last_name) {this.first_name = first_name; this.last_name = last_name; this.sibling = null;}} last me = new Person ("Fernando", "Doglio"); last sibling = new Person ("My", "Sibling"); me.sibling = sibling;sibling.sibling = me

In the above example, both objects refer to each other, so even if the me and sibling variables are out of scope, so, excluding references, each object internally has a strong reference to the other object. In practice, this means that these objects will never be collected. This is not a problem at all, unless you are using JS on a device with very little memory.

(2) enter weak reference

With some knowledge of strong references, weak references are easy to understand. Weak references are essentially a way to retain object references without affecting the behavior of the garbage collector. In the previous example, if sibling performance is set using weak reference constructions, then these objects can be collected. Another use case for weak references is the cache structure, because people do not want cached object internal references to be too active.

ClassMyCache {constructor () {this.cache= {}} add (key Obj) {this.cache [key] = newWeakRef (obj)} get (key) {let cachedRef = this.cache.deref () if (cachedRef) return cachedRef Returnfalse;}}

The above example is very basic, and using weak references is as simple as that. Just remember, if you want to access the referenced object, use the deref method. Because this is a weak reference, you need to check the return value of deref, and if it is undefined, the object no longer exists, otherwise it can be safely used (so do IF checking in the get method).

(3) Terminator

Now, in the top cherrie, finalizers allow you to react to the fact that weakly referenced objects collect garbage. Again, this is a highly concrete implementation, and here is how to use it:

Let registry = newFinalizationRegistry (value = > {console.log ("An object was removed! Message:", value)}) let myObject = {/ /.... } registry.register (myObject, "myObject was destroyed")

In essence, FinalizationRegistry is used to create the registry, and you need a callback function as a parameter. This function is used each time an object is collected (previously registered with the register method).

The register method itself is a refactoring method that specifies the object to be waited for, and its second parameter is the value passed to the initially defined callback when the registry is created. It is recommended that you use this method less, especially do not think about using it for business, but you can consider using it to solve some novel problems in special cases.

Promise.any

In this release, ECMAScript adds a way to handle multiple commitments at the same time. The any method can run multiple promises and solve later problems with the first promise, or wait until all promises fail and return to an AggregateError object (which is a subclass of the Error object).

So, what's the difference between any and race? In fact, as long as race has a promise to fulfill or fail, it will settle and return value. However, any will settle with the first settlement value, or wait for all the values to fail, and then recover all errors together.

Const promise1 = Promise.reject (0); const promise2 = newPromise ((resolve) = > setTimeout (resolve, 100,' quick')); const promise3 = newPromise ((resolve) = > setTimeout (resolve, 500,' slow')); const promises = [promise1, promise2, promise3]; Promise.race (promises). Then ((value) = > console.log (value)) / / logs the rejected promise / / vs Promise.any (promises) .then ((value) = > console.log (value)); / / logs "quick"

Note that any actually ignores the first rejected promise because there are other commitments being resolved, which is the main difference between race and any.

There are not many new features of ECMAScript2021, but the functions that have been accepted by the author seem to be very good! Be careful when using WeakRef and FinalizationRegistry, their functionality is very interesting, but they may deal with different results or behaviors under different operating conditions.

At this point, I believe you have a deeper understanding of "what are the functions of the new version of ECMAScript?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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