当前位置:网站首页>[JS] eight practical new functions of 1394-es2022
[JS] eight practical new functions of 1394-es2022
2022-07-28 16:50:00 【pingan8787】
english | https://betterprogramming.pub/es2022-features-javascript-a9f8f5dcba5a
new ES13 The specification has finally been released .
JavaScript Not an open source language , It is a need to follow ECMAScript The language of standard specification ,TC39 The committee is responsible for discussing and approving the release of new functions , that TC39 Who are they? ?
“ECMA International Of TC39 It's a group of JavaScript Developer 、 Implementer 、 Scholars, etc , They work with the community to maintain and develop JavaScript The definition of .” — TC39.es
Their release process consists of five stages , since 2015 Since then , They have been making annual releases , They usually take place in spring .
There are two ways to reference any ECMAScript edition :
By year : This new edition will be ES2022.
According to the number of iterations : This new edition will be the 13 Sub iteration , So it can be called ES13.
So what's new in this version ? What functions can we be excited about ?
01、 Regular expression matching index
at present , stay JavaScript Use in JavaScript Regex API when , Only the matching start index is returned . however , For some special advanced scenes , It is not enough .
As part of these specifications , Added a special logo d. By using it , Regular expressions API Will return a two-dimensional array as the key of the name index . It contains the start and end indexes of each match . If any named groups are captured in regular expressions , It will be indices.groups Object to return their start / End index , The named group name will be its key .
// a regex with a 'B' named group capture
const expr = /a+(?<B>b+)+c/d;
const result = expr.exec("aaabbbc")
// shows start-end matches + named group match
console.log(result.indices);
// prints [Array(2), Array(2), groups: {…}]
// showing the named 'B' group match
console.log(result.indices.groups['B'])
// prints [3, 6]View the original proposal ,https://github.com/tc39/proposal-regexp-match-indices
02、Top-level await
Before this proposal , Don't accept Top-level await, But there are some workarounds to simulate this behavior , But it has disadvantages .
Top-level await Features let us rely on modules to handle these Promise. This is an intuitive function .
But notice , It may change the execution order of modules , If one module depends on another with Top-level await Called module , The execution of this module will be suspended , until promise complete .
Let's take an example :
// users.js
export const users = await fetch('/users/lists');
// usage.js
import { users } from "./users.js";
// the module will wait for users to be fullfilled prior to executing any code
console.log(users);In the example above , The engine will wait for the user to complete the operation , then , Re execution usage.js Code on the module .
All in all , This is a good and intuitive function , You need to be careful with , Let's not abuse it .
View the original proposal here .https://github.com/tc39/proposal-top-level-await
03、.at( )
For a long time , Someone has been asking JavaScript Provide similar Python Array negative index accessor . Instead of doing array[array.length-1] To make simple array[-1]. It's impossible , because [] Symbols are also used for JavaScript Objects in the .
The accepted proposal takes a more practical approach .Array Object will now have a method to simulate the above behavior .
const array = [1,2,3,4,5,6]
// When used with positive index it is equal to [index]
array.at(0) // 1
array[0] // 1
// When used with negative index it mimicks the Python behaviour
array.at(-1) // 6
array.at(-2) // 5
array.at(-4) // 3View the original proposal ,https://github.com/tc39/proposal-relative-indexing-method
By the way , Since we are talking about arrays , Do you know that you can deconstruct array positions ?
const array = [1,2,3,4,5,6];
// Different ways of accessing the third position
const {3: third} = array; // third = 4
array.at(3) // 4
array[3] // 404、 addressable Object.prototype.hasOwnProperty
The following is just a good simplification , Already there. hasOwnProperty. however , It needs to call . therefore , It is common for many developers to end up doing this :
const x = { foo: "bar" };
// grabbing the hasOwnProperty function from prototype
const hasOwnProperty = Object.prototype.hasOwnProperty
// executing it with the x context
if (hasOwnProperty.call(x, "foo")) {
...
}Through these new specifications , One hasOwn Method is added to Object In prototype , Now? , We can simply do :
const x = { foo: "bar" };
// using the new Object method
if (Object.hasOwn(x, "foo")) {
...
}View the original proposal ,https://github.com/tc39/proposal-accessible-object-hasownproperty
05、Error Cause
Errors help us identify unexpected behavior in applications and react , However , Understand the root cause of deep nesting errors , Dealing with them correctly can become challenging , When capturing and re throwing them , We will lose stack trace information .
There is no clear agreement on how to deal with , Consider any error handling , We have at least 3 A choice :
async function fetchUserPreferences() {
try {
const users = await fetch('//user/preferences')
.catch(err => {
// What is the best way to wrap the error?
// 1. throw new Error('Failed to fetch preferences ' + err.message);
// 2. const wrapErr = new Error('Failed to fetch preferences');
// wrapErr.cause = err;
// throw wrapErr;
// 3. class CustomError extends Error {
// constructor(msg, cause) {
// super(msg);
// this.cause = cause;
// }
// }
// throw new CustomError('Failed to fetch preferences', err);
})
}
}
fetchUserPreferences();As part of these new specifications , We can construct a new error and keep the reference of the obtained error . We just need to put the object {cause: err} Pass to Errorconstructor.
It's all easier 、 Standard and easy to understand the error of deep nesting , Let's take an example :
async function fetcUserPreferences() {
try {
const users = await fetch('//user/preferences')
.catch(err => {
throw new Error('Failed to fetch user preferences, {cause: err});
})
}
}
fetcUserPreferences();Learn more about this proposal ,https://github.com/tc39/proposal-error-cause
06、Class Fields
Before this version , There is no proper way to create private fields , There are some ways to solve it by using promotion , But it is not an appropriate private field . But now it's simple , We just need to put # Characters are added to our variable declaration .
class Foo {
#iteration = 0;
increment() {
this.#iteration++;
}
logIteration() {
console.log(this.#iteration);
}
}
const x = new Foo();
// Uncaught SyntaxError: Private field '#iteration' must be declared in an enclosing class
x.#iteration
// works
x.increment();
// works
x.logIteration();Having private fields means that we have strong encapsulation boundaries , Cannot access class variables from outside , This shows that class Keywords are no longer just sugar grammar .
We can also create private methods :
class Foo {
#iteration = 0;
#auditIncrement() {
console.log('auditing');
}
increment() {
this.#iteration++;
this.#auditIncrement();
}
}
const x = new Foo();
// Uncaught SyntaxError: Private field '#auditIncrement' must be declared in an enclosing class
x.#auditIncrement
// works
x.increment();This function is related to class static blocks of private classes and ergonomic checks , We will see in the following content .
Learn more about this proposal ,https://github.com/tc39/proposal-class-fields
07、Class Static Block
As part of the new specification , We can now include static blocks in any class , They will only run once , And it is a good way to decorate or initialize some fields of the static end of the class .
We are not limited to using one block , We can have as many blocks as possible .
// will output 'one two three'
class A {
static {
console.log('one');
}
static {
console.log('two');
}
static {
console.log('three');
}
}They have a good Bonus , They get privileged access to private fields , You can use them to make some interesting patterns .
let getPrivateField;
class A {
#privateField;
constructor(x) {
this.#privateField = x;
}
static {
// it can access any private field
getPrivateField = (a) => a.#privateField;
}
}
const a = new A('foo');
// Works, foo is printed
console.log(getPrivateField(a));If we try to access the private variable from the external scope of the instance object , We will get that private members cannot be read from objects whose class does not declare it #privateField.
Learn more about this proposal ,https://github.com/tc39/proposal-class-static-block
08、Private Fields
The new private field is a great feature , however , In some static methods, it may become convenient to check whether the field is private .
Trying to call it outside the scope of the class will result in the same error we saw before .
class Foo {
#brand;
static isFoo(obj) {
return #brand in obj;
}
}
const x = new Foo();
// works, it returns true
Foo.isFoo(x);
// works, it returns false
Foo.isFoo({})
// Uncaught SyntaxError: Private field '#brand' must be declared in an enclosing class
#brand in xLearn more about this proposal .https://github.com/tc39/proposal-private-fields-in-in
The last thought
This is an interesting version , It provides many small and useful functions , for example at、private fields and error cause. Of course ,error cause It will bring a lot of clarity to our daily error tracking tasks .
Some advanced features , Such as top-level await, You need to understand them well before using them . They may cause unnecessary side effects in your code execution .
I hope this article can make you as interested in new ES2022 Norms are excited , Please remember to praise me , Pay attention to me .
Last , Thanks for reading .
边栏推荐
- Text filtering skills
- 关于web对接针式打印机问题,Lodop使用
- NoSQL introduction practice notes I
- Interesting kotlin 0x0a:fun with composition
- Multiple commands produce '... /xxx.app/assets.car' problem
- Microsoft question 100 - do it every day - question 11
- 日常开发方案设计指北
- PHP about problems such as memory overflow timeout caused by large amount of data exporting or traversing data
- How to set ticdc synchronization data to only synchronize the specified library?
- Leetcode daily practice - the number of digits in the offer 56 array of the sword finger
猜你喜欢

在abaqus中使用PyQt设计GUI

Quickly master kotlin set functions

Ansa secondary development - build ansa secondary development environment on Visual Studio code

排序2-冒泡排序与快速排序(递归加非递归讲解)

Sort 4-heap sort and massive TOPK problem

Early in the morning, pay Bora SMS to say that you won the "prize"? Dealing with server mining virus - kthreaddi

阿里大哥教你如何正确认识关于标准IO缓冲区的问题

Ansa secondary development - Introduction to interface development tools

有趣的 Kotlin 0x08:What am I

关于 CMS 垃圾回收器,你真的懂了吗?
随机推荐
First day of QT study
LwIP develops | socket | TCP | keepalive heartbeat mechanism
Introduction and implementation of stack (detailed explanation)
微软100题-天天做-第11题
Text filtering skills
队列的介绍与实现(详解)
“蔚来杯“2022牛客暑期多校训练营3 H.Hacker SAM+线段树/DP/分治(不带修查区间最大子段和)
PHP计算坐标距离
nowcode-学会删除链表中重复元素两题(详解)
Solve the width overflow of rich text pictures such as uniapp
MySQL CDC if the binlog log file is incomplete, can you read all the data in the full volume stage
ANSYS二次开发 - MFC界面调用ADPL文件
学会使用MySQL的Explain执行计划,SQL性能调优从此不再困难
有趣的 Kotlin 0x06:List minus list
“蔚来杯“2022牛客暑期多校训练营3 J.Journey 0-1最短路
Ansa secondary development - Introduction to interface development tools
ANSA二次开发 - 在PyCharm上搭建ANSA/META二次开发环境
Interesting kotlin 0x08:what am I
小程序:scroll-view默认滑倒最下面
Signal and slot mechanism of QT learning