当前位置:网站首页>ES2022 的 8 个实用的新功能
ES2022 的 8 个实用的新功能
2022-07-29 01:48:00 【油墨香^_^】
新的 ES13 规范终于发布了。
JavaScript 不是一种开源语言,它是一种需要遵循 ECMAScript 标准规范编写的语言,TC39 委员会负责讨论和批准新功能的发布, 那TC39他们是谁?
“ECMA International 的 TC39 是一群 JavaScript 开发人员、实施者、学者等,他们与社区合作维护和发展 JavaScript 的定义。” — TC39.es
他们的发布过程由五个阶段组成,自 2015 年以来,他们一直在进行年度发布,它们通常发生在春天举行发布。
有两种方法可以引用任何 ECMAScript 版本:
按年份:这个新版本将是 ES2022。
按其迭代次数:这个新版本将是第 13 次迭代,所以它可以被称为 ES13。
那么这次这个版本有什么新东西呢?我们可以对哪些功能感到兴奋?
01、正则表达式匹配索引
目前,在 JavaScript 中使用 JavaScript Regex API 时,仅返回匹配的开始索引。但是,对于一些特殊的高级场景,这还不够。
作为这些规范的一部分,添加了一个特殊的标志 d。通过使用它,正则表达式 API 将返回一个二维数组作为名索引的键。它包含每个匹配项的开始和结束索引。如果在正则表达式中捕获了任何命名组,它将在 indices.groups 对象中返回它们的开始/结束索引, 命名的组名将是它的键。
// a regex with a 'B' named group captureconst expr = /a+(?<B>b+)+c/d;const result = expr.exec("aaabbbc")// shows start-end matches + named group matchconsole.log(result.indices);// prints [Array(2), Array(2), groups: {…}]// showing the named 'B' group matchconsole.log(result.indices.groups['B'])// prints [3, 6]
查看原始提案,https://github.com/tc39/proposal-regexp-match-indices
02、Top-level await
在此提案之前,不接受Top-level await,但有一些变通方法可以模拟这种行为,但其有缺点。
Top-level await 特性让我们依靠模块来处理这些 Promise。这是一个直观的功能。
但是请注意,它可能会改变模块的执行顺序, 如果一个模块依赖于另一个具有Top-level await 调用的模块,则该模块的执行将暂停,直到 promise 完成。
让我们看一个例子:
// users.jsexport const users = await fetch('/users/lists');// usage.jsimport { users } from "./users.js";// the module will wait for users to be fullfilled prior to executing any codeconsole.log(users);
在上面的示例中,引擎将等待用户完成操作,然后,再执行 usage.js 模块上的代码。
总之,这是一个很好且直观的功能,需要小心使用,我们不要滥用它。
在此处查看原始提案。https://github.com/tc39/proposal-top-level-await
03、.at( )
长期以来,一直有人要求 JavaScript 提供类似 Python 的数组负索引访问器。而不是做 array[array.length-1] 来做简单的 array[-1]。这是不可能的,因为 [] 符号也用于 JavaScript 中的对象。
被接受的提案采取了更实际的方法。Array 对象现在将有一个方法来模拟上述行为。
const array = [1,2,3,4,5,6]// When used with positive index it is equal to [index]array.at(0) // 1array[0] // 1// When used with negative index it mimicks the Python behaviourarray.at(-1) // 6array.at(-2) // 5array.at(-4) // 3
查看原始提案,https://github.com/tc39/proposal-relative-indexing-method
顺便说一句,既然我们在谈论数组,你知道你可以解构数组位置吗?
const array = [1,2,3,4,5,6];// Different ways of accessing the third positionconst {3: third} = array; // third = 4array.at(3) // 4array[3] // 4
04、可访问的 Object.prototype.hasOwnProperty
以下只是一个很好的简化, 已经有了 hasOwnProperty。但是,它需要在我们想要执行的查找实例中调用。因此,许多开发人员最终会这样做是很常见的:
const x = { foo: "bar" };// grabbing the hasOwnProperty function from prototypeconst hasOwnProperty = Object.prototype.hasOwnProperty// executing it with the x contextif (hasOwnProperty.call(x, "foo")) {...}
通过这些新规范,一个 hasOwn 方法被添加到 Object 原型中,现在,我们可以简单地做:
const x = { foo: "bar" };// using the new Object methodif (Object.hasOwn(x, "foo")) {...}
查看原始提案,https://github.com/tc39/proposal-accessible-object-hasownproperty
05、Error Cause
错误帮助我们识别应用程序的意外行为并做出反应,然而,理解深层嵌套错误的根本原因,正确处理它们可能会变得具有挑战性,在捕获和重新抛出它们时,我们会丢失堆栈跟踪信息。
没有关于如何处理的明确协议,考虑到任何错误处理,我们至少有 3 个选择:
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();
作为这些新规范的一部分,我们可以构造一个新错误并保留获取的错误的引用。 我们只需将对象 {cause: err} 传递给 Errorconstructor。
这一切都变得更简单、标准且易于理解深度嵌套的错误, 让我们看一个例子:
async function fetcUserPreferences() {try {const users = await fetch('//user/preferences').catch(err => {throw new Error('Failed to fetch user preferences, {cause: err});})}}fetcUserPreferences();
了解有关该提案的更多信息,https://github.com/tc39/proposal-error-cause
06、Class Fields
在此版本之前,没有适当的方法来创建私有字段, 通过使用提升有一些方法可以解决它,但它不是一个适当的私有字段。 但现在很简单, 我们只需要将 # 字符添加到我们的变量声明中。
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 classx.#iteration// worksx.increment();// worksx.logIteration();
拥有私有字段意味着我们拥有强大的封装边界, 无法从外部访问类变量,这表明 class 关键字不再只是糖语法。
我们还可以创建私有方法:
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 classx.#auditIncrement// worksx.increment();
该功能与私有类的类静态块和人体工程学检查有关,我们将在接下来的内容中看到。
了解有关该提案的更多信息,https://github.com/tc39/proposal-class-fields
07、Class Static Block
作为新规范的一部分,我们现在可以在任何类中包含静态块,它们将只运行一次,并且是装饰或执行类静态端的某些字段初始化的好方法。
我们不限于使用一个块,我们可以拥有尽可能多的块。
// will output 'one two three'class A {static {console.log('one');}static {console.log('two');}static {console.log('three');}}
他们有一个不错的奖金,他们获得对私有字段的特权访问, 你可以用它们来做一些有趣的模式。
let getPrivateField;class A {#privateField;constructor(x) {this.#privateField = x;}static {// it can access any private fieldgetPrivateField = (a) => a.#privateField;}}const a = new A('foo');// Works, foo is printedconsole.log(getPrivateField(a));
如果我们尝试从实例对象的外部范围访问该私有变量,我们将得到无法从类未声明它的对象中读取私有成员#privateField。
了解有关该提案的更多信息,https://github.com/tc39/proposal-class-static-block
08、Private Fields
新的私有字段是一个很棒的功能,但是,在某些静态方法中检查字段是否为私有可能会变得很方便。
尝试在类范围之外调用它会导致我们之前看到的相同错误。
class Foo {#brand;static isFoo(obj) {return #brand in obj;}}const x = new Foo();// works, it returns trueFoo.isFoo(x);// works, it returns falseFoo.isFoo({})// Uncaught SyntaxError: Private field '#brand' must be declared in an enclosing class#brand in x
了解有关该提案的更多信息。https://github.com/tc39/proposal-private-fields-in-in
最后的想法
这是一个有趣的版本,它提供了许多小而有用的功能,例如 at、private fields和error cause。当然,error cause会给我们的日常错误跟踪任务带来很多清晰度。
一些高级功能,如top-level await,在使用它们之前需要很好地理解。它们可能在你的代码执行中产生不必要的副作用。
边栏推荐
- 密码安全如何保障?安全浏览器如何管理密码?
- 当我看源码的时候,我在想什么?
- JVM内存溢出在线分析Dump文件以及在线分析打开.hprof文件得出JVM运行报告jvisualvm怎么在线分析
- Leetcode 242. valid anagram
- 指针——黄金阶段
- Feynman learning method (symbol table)
- PS + PL heterogeneous multicore case development manual for Ti C6000 tms320c6678 DSP + zynq-7045 (2)
- Excel 打开包含汉字的 csv 文件出现乱码该怎么办?
- Flexible layout single selection
- Cookies and sessions
猜你喜欢

Control buzzer based on C51

一文读懂Okaleido Tiger近期动态,挖掘背后价值与潜力

应用系统中的报表开发成本值多少?

autoware中ndtmatching功能加载点云图坐标系修正的问题

Keil5 open the engineering prompt not found device solution

响应式织梦模板家装装饰类网站

Responsive dream weaving template home decoration website

How to customize a new tab in Duoyu security browser?

【质量】代码质量评价标准

Day 14: continued day 13 label related knowledge
随机推荐
ResNet50+k折交叉验证+数据增强+画图(准确率、召回率、F值)
第十四天:续第十三天标签相关知识
Installation guide for proftpd Secure FTP server with TLS encryption enabled
Problems encountered in special flow & properties property set instances and Solutions
Day 14: continued day 13 label related knowledge
Full solution of 3D model format | including more than 70 kinds of RVT, 3ds, DWG, FBX, IFC, osgb, obj, etc
Derivation of Euler angle differential equation
Rgbd point cloud down sampling
Interprocess communication - detailed explanation of the pipeline (explanation of graphic cases)
实验二:Arduino的三色灯实验
Cookie和Session
费曼学习法(符号表)
webview攻击
Responsive dream weaving template home decoration building materials website
进程间通信---对管道的详细讲解(图文案例讲解)
如何在多御安全浏览器中自定义新标签页?
Click back to the top JS
响应式织梦模板家装装饰类网站
Form verification hidden input box is displayed before verification
Responsive dream weaving template makeup website