Home  >  Article  >  Web Front-end  >  JavaScript updated to es

JavaScript updated to es

青灯夜游
青灯夜游Original
2022-10-31 17:40:393098browse

JavaScript has been updated to es13. On June 22, 2022, the 123rd Ecma Conference approved the ECMAScript2022 language specification, which means that it has now officially become a JavaScript standard; and ECMAScript2022 is the 13th iteration, so it can also be called ECMAScript13, or ES13 for short.

JavaScript updated to es

The operating environment of this tutorial: Windows 7 system, ECMAScript version 13, Dell G3 computer.

The new ES13 specification is finally released.

JavaScript is not an open source language. It is a language that needs to be written in compliance with the ECMAScript standard specification. The TC39 committee is responsible for discussing and approving the release of new features. So who are they TC39?

"ECMA International's TC39 is a group of JavaScript developers, implementers, academics, etc. who work with the community to maintain and evolve the definition of JavaScript." — TC39.es

Their release process is driven by Composed of five phases, they have been undergoing annual releases since 2015, and they usually take place in the spring.

On June 22, 2022, the 123rd Ecma Congress approved the ECMAScript 2022 language specification, which means that it is now officially a standard.

There are two ways to reference any ECMAScript version:

  • By year: This new version will be ES2022.

  • By its iteration number: This new version will be the 13th iteration, so it can be called ES13.

So what’s new in this version this time? What features can we be excited about?

01. Regular expression matching index

Currently, when using the JavaScript Regex API in JavaScript, only the beginning of the match is returned index. However, for some special advanced scenarios, this is not enough.

As part of these specifications, a special flag d was added. By using it, the regular expression API will return a two-dimensional array as the key of the name index. It contains the starting and ending index of each match. If any named groups are captured in the regex, it will return their start/end indices in the indices.groups object, with the named group name being its key.

// ✅ a regex with a 'B' named group capture
const expr = /a+(?<B>b+)+c/d;


const result = expr.exec("aaabbbc")


// ✅ shows start-end matches + named group match
console.log(result.indices);
// prints [Array(2), Array(2), groups: {…}]


// ✅ showing the named &#39;B&#39; group match
console.log(result.indices.groups[&#39;B&#39;])
// prints [3, 6]

View the original proposal, https://github.com/tc39/proposal-regexp-match-indices

02, Top-level await

Prior to this proposal, Top-level await was not accepted, but there were workarounds to simulate this behavior, which had drawbacks.

Top-level await feature allows us to rely on modules to handle these Promises. This is an intuitive feature.

But please note that it may change the execution order of modules. If a module depends on another module with a Top-level await call, the execution of the module will be suspended until the promise is completed.

Let’s look at an example:

// users.js
export const users = await fetch(&#39;/users/lists&#39;);


// usage.js
import { users } from "./users.js";
// ✅ the module will wait for users to be fullfilled prior to executing any code
console.log(users);

In the above example, the engine will wait for the user to complete the action before executing the code on the usage.js module.

All in all, this is a nice and intuitive feature that needs to be used with care and let's not abuse it.

View the original proposal here. https://github.com/tc39/proposal-top-level-await

03、.at( )

For a long time, There have been requests for JavaScript to provide Python-like negative index accessors for arrays. Instead of doing array[array.length-1] do simply array[-1]. This is not possible because the [] symbol is also used for objects in JavaScript.

The accepted proposal took a more practical approach. Array objects will now have a method to simulate the above behavior.

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


// ✅ When used with positive index it is equal to [index]
array.at(0) // 1
array[0] // 1


// ✅ When used with negative index it mimicks the Python behaviour
array.at(-1) // 6
array.at(-2) // 5
array.at(-4) // 3

See the original proposal, https://github.com/tc39/proposal-relative-indexing-method

By the way, since we are talking about arrays, you know you can destructure arrays Location?

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


// ✅ Different ways of accessing the third position
const {3: third} = array; // third = 4
array.at(3) // 4
array[3] // 4

04. Accessible Object.prototype.hasOwnProperty

The following is just a good simplification, there is already hasOwnProperty. However, it needs to be called within the lookup instance we want to perform. Therefore, it is common for many developers to end up doing this:

const x = { foo: "bar" };


// ✅ grabbing the hasOwnProperty function from prototype
const hasOwnProperty = Object.prototype.hasOwnProperty


// ✅ executing it with the x context
if (hasOwnProperty.call(x, "foo")) {
  ...
}

With these new specifications, a hasOwn method was added to the Object prototype, and now, we can simply do:

const x = { foo: "bar" };


// ✅ using the new Object method
if (Object.hasOwn(x, "foo")) {
  ...
}

View original proposal, https://github.com/tc39/proposal-accessible-object-hasownproperty

05、Error Cause

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

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

async function fetchUserPreferences() {
  try { 
    const users = await fetch(&#39;//user/preferences&#39;)
      .catch(err => {
        // What is the best way to wrap the error?
        // 1. throw new Error(&#39;Failed to fetch preferences &#39; + err.message);
        // 2. const wrapErr = new Error(&#39;Failed to fetch preferences&#39;);
        //    wrapErr.cause = err;
        //    throw wrapErr;
        // 3. class CustomError extends Error {
        //      constructor(msg, cause) {
        //        super(msg);
        //        this.cause = cause;
        //      }
        //    }
        //    throw new CustomError(&#39;Failed to fetch preferences&#39;, err);
      })
    }
}


fetchUserPreferences();

作为这些新规范的一部分,我们可以构造一个新错误并保留获取的错误的引用。 我们只需将对象 {cause: err} 传递给 Errorconstructor。

这一切都变得更简单、标准且易于理解深度嵌套的错误, 让我们看一个例子:

async function fetcUserPreferences() {
  try { 
    const users = await fetch(&#39;//user/preferences&#39;)
      .catch(err => {
        throw new Error(&#39;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 &#39;#iteration&#39; must be declared in an enclosing class
x.#iteration


// ✅ works
x.increment();


// ✅ works
x.logIteration();

拥有私有字段意味着我们拥有强大的封装边界, 无法从外部访问类变量,这表明 class 关键字不再只是糖语法。

我们还可以创建私有方法:

class Foo {
  #iteration = 0;


  #auditIncrement() {
    console.log(&#39;auditing&#39;);
  }


  increment() {
    this.#iteration++;
    this.#auditIncrement();
  }
}


const x = new Foo();


// ❌ Uncaught SyntaxError: Private field &#39;#auditIncrement&#39; must be declared in an enclosing class
x.#auditIncrement


// ✅ works
x.increment();

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

了解有关该提案的更多信息,https://github.com/tc39/proposal-class-fields

07、Class Static Block

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

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

// ✅ will output &#39;one two three&#39;
class A {
  static {
      console.log(&#39;one&#39;);
  }
  static {
      console.log(&#39;two&#39;);
  }
  static {
      console.log(&#39;three&#39;);
  }
}

他们有一个不错的奖金,他们获得对私有字段的特权访问, 你可以用它们来做一些有趣的模式。

let getPrivateField;


class A {
  #privateField;
  constructor(x) {
    this.#privateField = x;
  }
  static {
    // ✅ it can access any private field
    getPrivateField = (a) => a.#privateField;
  }
}


const a = new A(&#39;foo&#39;);
// ✅ Works, foo is printed
console.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 true
Foo.isFoo(x);


// ✅ works, it returns false
Foo.isFoo({})


// ❌ Uncaught SyntaxError: Private field &#39;#brand&#39; 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,在使用它们之前需要很好地理解。它们可能在你的代码执行中产生不必要的副作用。

【相关推荐:javascript视频教程编程视频

The above is the detailed content of JavaScript updated to es. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to use find() in es6Next article:How to use find() in es6