迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

ES2022 有什么新功能? 4 个最新的 JavaScript 功能

作者:迹忆客 最近更新:2022/10/31 浏览次数:

新的 ES13 规范终于发布了。 JavaScript 确实不是一种开源语言。 它是一种遵循 ECMAScript 标准规范编写的语言。 TC39 委员会负责讨论和批准新功能。 他们是谁?

“ECMA International 的 TC39 是一群 JavaScript 开发人员、实施者、学者等,他们与社区合作维护和发展 JavaScript 的定义。” — TC39.es

他们的发布过程由五个阶段组成。 自 2015 年以来,他们一直在进行年度发布。 它们通常发生在春天左右。

有两种方法可以引用任何 ECMAScript 版本:

  • 按年份:这个新版本将是 ES2022。
  • 按其迭代次数:这个新版本将是第 13 次迭代,所以它可以被称为 ES13。

那么这个版本有什么新东西呢? 我们可以对哪些功能感到兴奋?

正则表达式匹配索引

目前,在 JavaScript 中使用 JavaScript Regex API 时,仅返回匹配的开始索引。 但是,对于一些特殊的高级场景,这还不够。

作为这些规范的一部分,添加了一个特殊的标志 d。 通过使用它,正则表达式 API 将返回一个二维数组作为名为 indices 的键。 它包含每个匹配项的 startend 索引。 如果在正则表达式中捕获了任何命名组,它将在 indices.groups 对象中返回它们的开始/结束索引。 命名的组名将是它的键。

// ✅ 带有“B”命名组捕获的正则表达式
const expr = /a+(?<B>b+)+c/d;

const result = expr.exec("aaabbbc")

// ✅ 显示 start-end 匹配 + 命名组匹配
console.log(result.indices);
// prints [Array(2), Array(2), groups: {…}]

// ✅ 显示名为“B”的组匹配
console.log(result.indices.groups['B'])
// prints [3, 6]

Top-level await

在此提案之前,不接受 Top-level await。 有一些变通方法可以模拟这种行为,但都有其缺点。

Top-level await 特性让我们依靠模块来处理这些 Promise。 这是一个直观的功能。 但是请注意,它可能会改变模块的执行顺序。 如果一个模块依赖于另一个具有顶级 await 调用的模块,则该模块的执行将暂停,直到 promise 完成。

让我们看一个例子:

// users.js
export const users = await fetch('/users/lists');

// usage.js
import { users } from "./users.js";
// ✅ 该模块将在执行任何代码之前等待用户完成
console.log(users);

在上面的示例中,引擎将等待用户完成操作,然后再执行 usage.js 模块上的代码。

总之,这是一个很好且直观的功能,需要小心使用。 我们不想滥用它。


.at()

长期以来,一直有人要求 JavaScript 提供类似 Python 的数组负索引访问器。 而不是做 array[array.length-1] 来做简单的 array[-1]。 这是不可能的,因为 [] 符号也用于 JavaScript 中的对象。

被接受的提案采取了更实际的方法。 Array 对象现在将有一个方法来模拟上述行为。

const array = [1,2,3,4,5,6]

// ✅ 当与正索引一起使用时,它等于 [index]
array.at(0) // 1
array[0] // 1

// ✅ 当与负索引一起使用时,它模仿 Python 行为
array.at(-1) // 6
array.at(-2) // 5
array.at(-4) // 3

顺便说一句,既然我们在谈论数组,你知道你可以解构数组位置吗? 👌

const array = [1,2,3,4,5,6];

// ✅ 访问第三个位置的不同方式
const {3: third} = array; // third = 4
array.at(3) // 4
array[3] // 4

可访问的 Object.prototype.hasOwnProperty

以下只是一个很好的简化。 已经有了 hasOwnProperty。 但是,它需要在我们想要执行的查找实例中调用。 因此,许多开发人员最终会这样做是很常见的:

const x = { foo: "bar" };

// ✅ 从原型中获取 hasOwnProperty 函数
const hasOwnProperty = Object.prototype.hasOwnProperty

// ✅ 使用 x 上下文执行它
if (hasOwnProperty.call(x, "foo")) {
  ...
}

通过这些新规范,一个 hasOwn 方法被添加到 Object 原型中。 现在,我们可以简单地做:

const x = { foo: "bar" };

// ✅ 使用新的 Object 方法
if (Object.hasOwn(x, "foo")) {
  ...
} 

错误原因

错误帮助我们识别应用程序的意外行为并做出反应。 然而,理解深层嵌套错误的根本原因甚至正确处理它们可能变得具有挑战性。 在捕获和重新抛出它们时,我们会丢失堆栈跟踪信息。

没有关于如何处理的明确协议。 考虑到任何错误处理,我们至少有 3 个选择:

async function fetchUserPreferences() {
  try { 
    const users = await fetch('//user/preferences')
      .catch(err => {
        // 封装错误的最佳方法是什么?
        // 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();

类字段

在此版本之前,没有适当的方法来创建私有字段。 通过使用提升有一些方法可以解决它,但它不是一个适当的私有字段。 现在很简单。 我们只需要将 # 字符添加到我们的变量声明中。

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();

拥有私有字段意味着我们拥有强大的封装边界。 无法从外部访问类变量。 这表明 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 class
x.#auditIncrement

// ✅ works
x.increment();

该功能与私有类的类静态块和人体工程学检查有关,我们将在下面看到。


类 static 静态块

作为新规范的一部分,我们现在可以在任何类中包含静态块。 它们将只运行一次,并且是装饰或执行类静态端的某些字段初始化的好方法。

我们不限于使用一个块,我们可以拥有尽可能多的块。

// ✅ 将要输出 '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 {
    // ✅ 它可以访问任何私有字段
    getPrivateField = (a) => a.#privateField;
  }
}

const a = new A('foo');
// ✅ 打印 foo
console.log(getPrivateField(a));

如果我们尝试从实例对象的外部范围访问该私有变量,我们将得到 Cannot read private member #privateField from an object whose class did not declare it. 错误。


私有字段的检查

新的 private 字段是一个很棒的功能。 但是,在某些静态方法中检查字段是否为私有可能会变得很方便。

尝试在类范围之外调用它会导致我们之前看到的相同错误。

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

总结

这是一个有趣的版本,它提供了许多小而有用的功能,例如 at、私有字段和错误原因。 当然,错误原因会给我们的日常错误跟踪任务带来很多清晰度。

一些高级功能,如 Top-level await,在使用它们之前需要很好地理解。 它们可能在您的代码执行中产生不必要的副作用

我希望这篇文章能大家对新的 ES2022 规范感到兴奋。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

JavaScript POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便