当前位置:网站首页>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)); // 4Except for arrays , The same applies to strings :
const str = "hello world";
console.log(str[str.length - 1]); // d
console.log(str.at(-1)); // d4、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 classMethods 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); // falseInstances 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:undefinedStatic 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:bluesummary
That's all ES2022 Several new features released , Is there anything you know ?
If the article is inappropriate , Please grant me your advice .
边栏推荐
- Cloud Vulnerability Global Database
- Share some feelings of a programmer who has experienced layoffs twice a year
- pytorch训练自己网络后可视化特征图谱的代码
- 倒置残差的理解
- 好友新书发布,祝贺(送福利)
- 轉載csdn文章操作
- twenty million two hundred and twenty thousand seven hundred and one
- Object memory layout
- Easyexcel complex data export
- QT uses ffmpeg4 to convert the qimage of ARGB to yuv422p
猜你喜欢
随机推荐
Mysql database detailed learning tutorial
Configure filter
SAP 智能机器人流程自动化(iRPA)解决方案分享
Wechat open platform scanning code login [easy to understand]
Origin2018安装教程「建议收藏」
ECMAScript 2022 正式发布,有你了解过的吗?
Slope compensation
Kubernetes create service access pod
深度学习--数据操作
Fiori applications are shared through the enhancement of adaptation project
正则系列之量词(Quantifiers)
转--深入LUA脚本语言,让你彻底明白调试原理
MySQL MHA high availability configuration and failover
陈天奇的机器学习编译课(免费)
Efficiency improvement - encourage personalized container development environment
cvpr2022 human pose estiamtion
Slope compensation
Appium自动化测试基础 — 补充:Desired Capabilities参数介绍
[C language] detailed explanation of malloc function [easy to understand]
分享一个一年经历两次裁员的程序员的一些感触









