当前位置:网站首页>Eight practical new functions of es2022
Eight practical new functions of es2022
2022-07-29 02:25:00 【Ink fragrance^_^】
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) // 3
View 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] // 4
04、 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 x
Learn 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 .
边栏推荐
- Experiment 2: Arduino's tricolor lamp experiment
- MySQL之数据查询(多表查询)
- 会议OA之会议通知
- QT memory management tips
- [upload picture 2-cropable]
- 发布融资需求1.29亿元,大科城项目路演持续浇灌科创“好苗子”
- Navigation -- realize data transmission and data sharing between fragments
- 详解JS的四种异步解决方案:回调函数、Promise、Generator、async/await
- Ignore wechat font settings
- 数据安全与隐私计算峰会-安全求交集在隐私计算中的发展和应用:学习
猜你喜欢
Day 14: continued day 13 label related knowledge
awvs无法启动问题
NPM install reports an error: eperm: operation not permitted, rename
详解异步任务:任务的状态及生命周期管理
Remember error scheduler once Asynceventqueue: dropping event from queue shared causes OOM
ES6事件绑定(v-on用法)
Summarize in the middle of the year | talk to yourself, live in the present, and count every step
裂开了,一次连接池参数导致的雪崩问题
Jmeter之BeanShell生成MD5加密数据写入数据库
自定义mvc原理和框架实现
随机推荐
Data query of MySQL (multi table query)
[golang learning notes 2.2] map, structure and interface
特殊流&Properties属性集实例遇到的问题及解决方法
外包公司“混”了2年,我只认真做了5件事,如今顺利拿到字节 Offer。
Resolve the conflict with vetur when using eslint, resulting in double quotation marks and comma at the end of saving
STM32 DMA receives serial port data
第3章业务功能开发(线索备注的删除和修改)
mobile-picker.js
Read the recent trends of okaleido tiger and tap the value and potential behind it
【ONE·Data || 数组堆简单实现及其延伸】
Prevent repeated clicks
高效使用浏览器的5个小技巧,第1个技巧最实用
Data security and privacy computing summit - development and application of security intersection in privacy Computing: Learning
Detailed explanation of IVX low code platform series -- Overview (II)
我被这个浏览了 746000 次的问题惊住了
Idea connection database
Interprocess communication - detailed explanation of the pipeline (explanation of graphic cases)
“蔚来杯“2022牛客暑期多校训练营3,签到题CAJHF
MySQL stores JSON format data
JVM memory overflow online analysis dump file and online analysis open.Hprof file to get JVM operation report how jvisualvm online analysis