Introduction

ES12 is a version issued by the ECMA Association in June 2021. Because it is the twelfth version of ECMAScript, it is also called ES12.

It has been a month since ES12 was released, so what are the new features and differences in ES12? Let's take a look.

Basically ES12 introduces the replaceAll method to operate on String, Promise.any to combine operations on Promise, AggregateError to represent a collection of multiple errors, new logical operators??=, &&=, ||= , Weak reference WeakRef, FinalizationRegistry is used for garbage collection registration, a number separator 1_000, more accurate array sort method Array.prototype.sort.

The following article will explain one by one.

replaceAll

Friends who are familiar with Java should know that there are two methods for string replacement in Java, namely replace and replaceAll. The difference between them is that replace is to replace strings, and replaceAll is to perform regular expression matching.

But in javascript, the meaning of the two is different. In JS, replace is to replace the first string, and replaceAll is to replace all strings literally. Let's take an example:

const string="flydean is a good fly"
console.log(string.replace("fly", "butterfly"));

The above value returns:

butterflydean is a good fly

If you use replaceAll instead:

const string="flydean is a good fly"
console.log(string.replaceAll("fly", "butterfly"));
butterflydean is a good butterfly

Private method

Since JS has the concept of a class, you can define methods in the class and call it through the instantiated class, as shown below:

class Student {
  getAge() {
    console.log("永远18岁")
  }
}

student= new Student();
student.getAge();

The result of running the above code:

"永远18岁"

But if we don't want the getAge() method to be directly exposed for external use, that is to say, we want getAge() to be a private method, then just add # in front of the method.

class Student {
  #getAge() {
    console.log("永远18岁")
  }
}

student= new Student();
student.getAge();

Run the same, then you will get the following error message:

Error: student.getAge is not a function

How to deal with it? We know that private methods can be called inside methods, so we only need to create a public method, and then call the private method in this public method, as shown below:

class Student {
  #getAge() {
    console.log("永远18岁")
  }
  
  getPublicAge(){
    this.#getAge();
  }
 
}

student= new Student();
student.getPublicAge();

We can get the same result.

Private property

We talked about private methods above, so how do we deal with private properties?

Usually, for attributes, we can modify them with the get modifier, and then we can access them directly through the attribute name:

class Student {
  get Age() {
    return 18;
  }
 
}

student= new Student();
console.log(student.Age);

As a result, we will get an output of 18.

Similarly, you can add # in front of the attribute name to make it a private variable, as shown below:

class Student {
  get #Age() {
    return 18;
  }
 
}

student= new Student();
console.log(student.Age);

The above code will output undefined.

To access the above-mentioned private properties, you can use public properties to call the private property methods:

class Student {
  get #Age() {
    return 18;
  }
   get publicAge() {
    return this.#Age
  }
}

student= new Student();
console.log(student.publicAge);

very useful.

Promise.any() and AggregateError

promise.any can return the result of any pre-resolve. In real applications, this situation is very common. Let's simulate an example:

const prom1 = new Promise((resolve, reject) => {
  setTimeout(
    () => resolve("promise one"),
    Math.floor(Math.random() * 100)
  );
});
const prom2 = new Promise((resolve, reject) => {
  setTimeout(
    () => resolve("promise two"),
    Math.floor(Math.random() * 100)
  );
});
const prom3 = new Promise((resolve, reject) => {
  setTimeout(
    () => resolve("promise three"),
    Math.floor(Math.random() * 100)
  );
});

(async function() {
  const result = await Promise.any([prom1, prom2, prom3]);
  console.log(result); 
})();

The above code can randomly output promise one, promise two, and promise three.

If you change the above code to reject all, then an AggregateError will be thrown:

const prom1 = new Promise((resolve, reject) => {
  setTimeout(
    () => reject("promise one rejected"),
    Math.floor(Math.random() * 100)
  );
});
const prom2 = new Promise((resolve, reject) => {
  setTimeout(
    () => reject("promise two rejected"),
    Math.floor(Math.random() * 100)
  );
});
const prom3 = new Promise((resolve, reject) => {
  setTimeout(
    () => reject("promise three rejected"),
    Math.floor(Math.random() * 100)
  );
});

try{
(async function() {
  const result = await Promise.any([prom1, prom2, prom3]);
  console.log(result); 
})();
} catch(error) {
  console.log(error.errors);
}

The error reported is as follows:

Uncaught (in promise) AggregateError: No Promise in Promise.any was resolved
Note that AggregateError must be thrown after all promises are rejected. If some of the promises are successful, then a successful result will be returned.

Number separator

This new feature appears to make it easier for programmers to read the code. If the number is relatively large, it may not look so obvious at a glance, such as the following long number:

const number= 123456789;

You can't tell at a glance how big this number is, so ES12 provides a number separator _.

The delimiter can not only divide the decimal system, but also divide the data of the two net value or the sixteen net value, which is very easy to use.

const number = 1_000_000_000_000;
const binary = 0b1010_0101_1111_1101;
const hex = 0xAF_BF_C3;

The above examples represent decimal, binary and hexadecimal data respectively, which is very intuitive and easy to use.

New logical operators

We know that && and || are operators used to perform logical operations.

for example:

1 && 2 
1 || 2 

For other operations, ES12 provides binary operators of && and ||, as follows:

var x = 1;
var y = 2;
x &&= y;
x ||= y;

In addition, binary operators of ?? are also provided, such as:

var x;
var y = 2;
x ??= y;

The meaning of the above code is to determine whether x is empty, and if it is empty, then assign the value of y to x.

Summarize

Several new features of ES12 are quite practical, you can try them.

This article has been included in http://www.flydean.com/ecmascript-12/

The most popular interpretation, the most profound dry goods, the most concise tutorial, and many tips you don't know are waiting for you to discover!

Welcome to pay attention to my official account: "Program those things", know technology, know you better!


flydean
890 声望432 粉丝

欢迎访问我的个人网站:www.flydean.com