当前位置:网站首页>ECMAScript 2022 was officially released. Have you heard about it?
ECMAScript 2022 was officially released. Have you heard about it?
2022-07-01 22:52:00 【Front end non release Leo】
Catalog
1、Top-level await( top floor await)
5、 Regular expression matching index
Preface
2022 year 6 month 22 Japan , The first 123 the ECMA The General Assembly approved ECMAScript 2022 language norm , This means that it is now officially the standard . So let's see ECMAScript 2022 What's new , Is there anything you know .
Text
One 、 The overview
1、Top-level await( top floor await)
2、Object.hasOwn()
3、at()
4、error.cause
5、 Regular expression matching index
6、 class
Two 、 detailed
1、Top-level await( top floor await)
stay ES2017 in , Introduced async await, Simplify Promise Use , however await Keywords can only be found in async Function . If used outside of asynchronous functions await You're going to report a mistake .
top floor await Allow us to async Use out of function await keyword . It allows modules to act as large asynchronous functions , Through the top floor await, These modules can wait for resources to load , In this way, other modules that import these modules will wait for the resources to load before executing the code .
Because await Only in async Use in a function , Therefore, the module needs to wrap the code in async Function to include await:
// test.js
let users;
export const fetchUsers = async () => {
const res = await fetch('https://www.leoTest.com/users');
users = res.json();
}
fetchUsers();
export { users };
// usingAwait.js
import { users } from './test.js';
console.log('users: ', users);
console.log('usingAwait module');
There will be a disadvantage , Directly imported users Would be undefined. If we need access to get it , After asynchronous execution :
// usingAwait.js
import { users } from './test.js';
console.log('users:', users); // Direct access ,undefined
setTimeout(() => {
console.log('users:', users); // Wait for asynchronous execution to complete , Visit again
}, 100);
console.log('usingAwait module');
Of course , This method is not fully implemented , Because if the asynchronous function takes more time to execute than 100 millisecond , It won't work ,users Still undefined.
Another way is to export a Promise, Let the import module know that the data is ready :
// test.js
export default (async () => { // Export a Promise
const res = await fetch('https://www.leoTest.com/users');
users = res.json();
})();
export { users };
// usingAwait.js
import Promise, { users } from './test.js';
Promise.then(() => {
console.log('usingAwait module');
setTimeout(() => console.log('users:', users), 100);
});
Although this method seems to get the expected results , But there are some limitations : The import module must understand this pattern to use it correctly .
and top-level await( top floor await) Can solve these problems :
// test.js
const res = await fetch('https://www.leoTest.com/users'); // Use the top layer await
const users = res.json();
export { users };
// usingAwait.js
import { users } from './test.js';
console.log(users);
console.log('usingAwait module');
At this time users You must wait until the asynchronous execution is completed before accessing .
top floor await It will be very useful in the following scenarios :
① Dynamic load module
const str = await import(`/i18n/${navigator.language}`);
② Resource initialization
const con = await dbConnector();
③ Dependency fallback
let translations;
try {
translations = await import('https://app.fr.json');
} catch {
translations = await import('https://fallback.en.json');
}
2、Object.hasOwn()
Before that , We can use Object.prototype.hasOwnProperty() To check whether a property belongs to the object .
Object.hasOwn() Feature is a more concise 、 More reliable method to check whether the property is directly set on the object :
const example = {
name: 'leo'
};
console.log(Object.prototype.hasOwnProperty.call(example, 'name'));
// More brief way
console.log(Object.hasOwn(example, 'name'));
3、at()
at() Is an array method , Used to get array elements by given index . When the given index is positive , This new method has the same behavior as using bracket notation access . When a negative integer index is given , It will start from the last item of the array :
const arr = [0,1,2,3,4,5];
console.log(arr[0]); // 0
console.log(arr.at(0)); // 0
console.log(arr[arr.length - 1]); // 5
console.log(arr.at(-1)); // 5
console.log(arr[arr.lenght - 2]); // 4
console.log(arr.at(-2)); // 4
Except for arrays , The same applies to strings :
const str = "hello world";
console.log(str[str.length - 1]); // d
console.log(str.at(-1)); // d
4、error.cause
stay ES2022 Specification ,new Error() You can specify the cause of it in :
function readFiles(filePaths) {
return filePaths.map(
(filePath) => {
try {
// ···
} catch (error) {
throw new Error(
`While processing ${filePath}`,
{cause: error}
);
}
});
}
5、 Regular expression matching index
This feature allows us to take advantage of d Character to indicate the start and end indexes of the string we want to match . before , An array containing extracted strings and index information can only be obtained during a string matching operation . In some cases , This is not enough . therefore , In this specification , If the flag is set /d, You will get an extra array with start and end indexes .
const matchObj = /(a+)(b+)/d.exec('aaaabb');
console.log(matchObj[1]); // 'aaaa'
console.log(matchObj[2]); // 'bb'
because /d Existence of identity ,matchObj There's another property .indices, It is used to record each number group captured :
console.log(matchObj.indices[1]); // [0, 4]
console.log(matchObj.indices[2]); // [4, 6]
6、 class
① Public instance fields
Public class fields allow us to use assignment operators (=) Add instance properties to the class definition . Here is an example of a counter :
import React, { Component } from "react";
export class Incrementor extends Component {
constructor() {
super();
this.state = {
count: 0,
};
this.increment = this.increment.bind(this);
}
increment() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<button onClick={this.increment}>Increment: {this.state.count}</button>
);
}
}
In this case , The instance field and binding method are defined in the constructor , Through the new class Syntax , Can make the code more intuitive . The new public class field syntax allows us to add instance attributes directly to the class as attributes , Instead of using constructor methods . This simplifies the definition of classes , Make the code more concise 、 Can be read :
import React from "react";
export class Incrementor extends React.Component {
state = { count: 0 };
increment = () => this.setState({ count: this.state.count + 1 });
render = () => (
<button onClick={this.increment}>Increment: {this.state.count}</button>
);
}
Some of my friends may have found out , This function has been available for a long time . But it is not standard yet ECMAScript, Not on by default , If you use create-react-app
establish react project , Then it is enabled by default , Otherwise we have to use the correct babel Plug in can be used normally (@babel/preset-env
).
Here are some considerations for public instance fields :
⑴ The public instance field exists on each created class instance . They are either Object.defineProperty() Add , Or add... When constructing in the base class , Or in the subclass super() Add... After returning
class Incrementor {
count = 0
}
const instance = new Incrementor();
console.log(instance.count); // 0
⑵ Uninitialized fields are automatically set to undefined
class Incrementor {
count
}
const instance = new Incrementor();
console.log(instance.count); // undefined
⑶ You can calculate fields
const PREFIX = 'main';
class Incrementor {
[`${PREFIX}Count`] = 0
}
const instance = new Incrementor();
console.log(instance.mainCount); // 0
② Private instance fields 、 Methods and accessors
By default ,ES6 All properties in are public , It can be checked or modified outside the class :
class TimeTracker {
name = 'leo';
project = 'blog';
hours = 0;
set addHours(hour) {
this.hours += hour;
}
get timeSheet() {
return `${this.name} works ${this.hours || 'nothing'} hours on ${this.project}`;
}
}
let person = new TimeTracker();
person.addHours = 2; // standard setter
person.hours = 4; // Bypass setter Set it up
person.timeSheet; // 'leo works 4 hours on blog'
You can see , There is nothing in the class to prevent you from calling setter To change properties .
Private class fields will use # Prefix definition , In the example above , You can modify it to include private class fields , To prevent changing properties outside of class methods :
class TimeTracker {
name = 'leo';
project = 'blog';
#hours = 0; // Private class fields
set addHours(hour) {
this.#hours += hour;
}
get timeSheet() {
return `${this.name} works ${this.#hours || 'nothing'} hours on ${this.project}`;
}
}
let person = new TimeTracker();
person.addHours = 4; // standard setter
person.timeSheet // 'leo works 4 hours on blog'
When trying in setter Method , You're going to report a mistake :
person.hours = 4; // Error Private field '#hours' must be declared in an enclosing class
Methods or getter/setter Set as private , Just prefix the method names with # that will do :
class TimeTracker {
name = 'leo';
project = 'blog';
#hours = 0; // Private class fields
set #addHours(hour) {
this.#hours += hour;
}
get #timeSheet() {
return `${this.name} works ${this.#hours || 'nothing'} hours on ${this.project}`;
}
constructor(hours) {
this.#addHours = hours;
console.log(this.#timeSheet);
}
}
let person = new TimeTracker(4); // 'leo works 4 hours on blog'
③ Static public fields
stay ES6 in , You cannot access static fields or methods in every instance of a class , Can only be accessed in the prototype .ES2022 Provides a way to JavaScript Use in static Keyword to declare a method of a static class field :
class Shape {
static color = 'blue';
static getColor() {
return this.color;
}
getMessage() {
return `color:${this.color}` ;
}
}
Static fields and methods can be accessed from the class itself :
console.log(Shape.color); // blue
console.log(Shape.getColor()); // blue
console.log('color' in Shape); // true
console.log('getColor' in Shape); // true
console.log('getMessage' in Shape); // false
Instances cannot access static fields and methods :
const shapeInstance = new Shape();
console.log(shapeInstance.color); // undefined
console.log(shapeInstance.getColor); // undefined
console.log(shapeInstance.getMessage()); // color:undefined
Static fields can only be accessed through static methods :
console.log(Shape.getColor()); // blue
console.log(Shape.getMessage()); //TypeError: Shape.getMessage is not a function
there Shape.getMessage()
It's a mistake , because getMessage
Not a static function , So it can't pass the class name Shape
visit . This problem can be solved in the following ways :
getMessage() {
return `color:${Shape.color}` ;
}
Static fields and methods are inherited from the parent class :
class Rectangle extends Shape { } // Inherit
console.log(Rectangle.color); // blue
console.log(Rectangle.getColor()); // blue
console.log('color' in Rectangle); // true
console.log('getColor' in Rectangle); // true
console.log('getMessage' in Rectangle); // false
④ Static private fields and methods
Same as private instance fields and methods , Static private fields and methods also use hashes # Prefix to define :
class Shape {
static #color = 'blue';
static #getColor() {
return this.#color;
}
getMessage() {
return `color:${Shape.#getColor()}` ;
}
}
const shapeInstance = new Shape();
shapeInstance.getMessage(); // color:blue
Private static fields have a limitation , That is, only classes that define private static fields can access this field . This may be in use this
It leads to unexpected situations :
class Shape {
static #color = 'blue';
static #getColor() {
return this.#color;
}
static getMessage() {
return `color:${this.#color}` ;
}
getMessageNonStatic() {
return `color:${this.#getColor()}` ;
}
}
class Rectangle extends Shape {}
console.log(Rectangle.getMessage()); // Uncaught TypeError: Cannot read private member #color from an object whose class did not declare it
const rectangle = new Rectangle();
console.log(rectangle.getMessageNonStatic()); // TypeError: Cannot read private member #getColor from an object whose class did not declare it
In this case ,this
Pointing to Rectangle
class , It does not have access to private fields #color
. When we try to call Rectangle.getMessage()
when , It cannot read #color
And throw TypeError
. It can be modified in this way :
class Shape {
static #color = 'blue';
static #getColor() {
return this.#color;
}
static getMessage() {
return `${Shape.#color}`;
}
getMessageNonStatic() {
return `color:${Shape.#getColor()} color`;
}
}
class Rectangle extends Shape {}
console.log(Rectangle.getMessage()); // color:blue
const rectangle = new Rectangle();
console.log(rectangle.getMessageNonStatic()); // color:blue
summary
That's all ES2022 Several new features released , Is there anything you know ?
If the article is inappropriate , Please grant me your advice .
边栏推荐
- 104. SAP ui5 table control supports multi select and how to select multiple table row items at a time with code
- Clean up system cache and free memory under Linux
- 隐藏用户的创建和使用
- 【无标题】
- 死锁的处理策略—预防死锁、避免死锁、检测和解除死锁
- Intelligent computing architecture design of Internet
- Fiori 应用通过 Adaptation Project 的增强方式分享
- SAP UI5 应用开发教程之一百零四 - SAP UI5 表格控件的支持复选(Multi-Select)以及如何用代码一次选中多个表格行项目
- Origin2018 installation tutorial "recommended collection"
- 转--深入LUA脚本语言,让你彻底明白调试原理
猜你喜欢
随机推荐
MySQL中对于索引的理解
Deep learning -- data operation
转--利用C语言中的setjmp和longjmp,来实现异常捕获和协程
[daily training] 66 add one-tenth
多图预警~ 华为 ECS 与 阿里云 ECS 对比实战
Tourism Management System
[jetcache] how to use jetcache
旅游管理系统
Sogou wechat app reverse (II) so layer
Resttemplate remote call tool class
The median salary of TSMC's global employees is about 460000, and the CEO is about 8.99 million; Apple raised the price of iPhone in Japan; VIM 9.0 release | geek headlines
Arlo's thinking after confusion
Talk about what parameters ZABBIX monitors
rxjs Observable of 操作符的单步调试分析
激发新动能 多地发力数字经济
小红书Scheme跳转到指定页面
好友新书发布,祝贺(送福利)
搜狗微信APP逆向(二)so层
447-哔哩哔哩面经1
MySQL MHA high availability configuration and failover