【JS】1394- ES2022 的 8 个实用的新功能
英文 | https://betterprogramming.pub/es2022-features-javascript-a9f8f5dcba5a
按年份:这个新版本将是 ES2022。 按其迭代次数:这个新版本将是第 13 次迭代,所以它可以被称为 ES13。
// ✅ 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 {increment() {this.}logIteration() {console.log(this.}}const x = new Foo();// ❌ Uncaught SyntaxError: Private field '#iteration' must be declared in an enclosing classx.// ✅ worksx.increment();// ✅ worksx.logIteration();
拥有私有字段意味着我们拥有强大的封装边界, 无法从外部访问类变量,这表明 class 关键字不再只是糖语法。
我们还可以创建私有方法:
class Foo {console.log('auditing');}increment() {this.this.}}const x = new Foo();// ❌ Uncaught SyntaxError: Private field '#auditIncrement' must be declared in an enclosing classx.// ✅ 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 {static isFoo(obj) {return}}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
了解有关该提案的更多信息。https://github.com/tc39/proposal-private-fields-in-in
最后的想法
这是一个有趣的版本,它提供了许多小而有用的功能,例如 at、private fields和error cause。当然,error cause会给我们的日常错误跟踪任务带来很多清晰度。
一些高级功能,如top-level await,在使用它们之前需要很好地理解。它们可能在你的代码执行中产生不必要的副作用。
我希望这篇文章能让你和我一样对新的 ES2022 规范感到兴奋,请记得点赞我,关注我。
最后,感谢你的阅读。
