search
HomeWeb Front-endFront-end Q&AJavaScript updated to es

JavaScript updated to es

Oct 31, 2022 pm 05:40 PM
javascript

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
React: The Foundation for Modern Frontend DevelopmentReact: The Foundation for Modern Frontend DevelopmentApr 19, 2025 am 12:23 AM

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

The Future of React: Trends and Innovations in Web DevelopmentThe Future of React: Trends and Innovations in Web DevelopmentApr 19, 2025 am 12:22 AM

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

React: A Powerful Tool for Building UI ComponentsReact: A Powerful Tool for Building UI ComponentsApr 19, 2025 am 12:22 AM

React is a JavaScript library for building user interfaces. Its core idea is to build UI through componentization. 1. Components are the basic unit of React, encapsulating UI logic and styles. 2. Virtual DOM and state management are the key to component work, and state is updated through setState. 3. The life cycle includes three stages: mount, update and uninstall. The performance can be optimized using reasonably. 4. Use useState and ContextAPI to manage state, improve component reusability and global state management. 5. Common errors include improper status updates and performance issues, which can be debugged through ReactDevTools. 6. Performance optimization suggestions include using memo, avoiding unnecessary re-rendering, and using us

Using React with HTML: Rendering Components and DataUsing React with HTML: Rendering Components and DataApr 19, 2025 am 12:19 AM

Using HTML to render components and data in React can be achieved through the following steps: Using JSX syntax: React uses JSX syntax to embed HTML structures into JavaScript code, and operates the DOM after compilation. Components are combined with HTML: React components pass data through props and dynamically generate HTML content, such as. Data flow management: React's data flow is one-way, passed from the parent component to the child component, ensuring that the data flow is controllable, such as App components passing name to Greeting. Basic usage example: Use map function to render a list, you need to add a key attribute, such as rendering a fruit list. Advanced usage example: Use the useState hook to manage state and implement dynamics

React's Purpose: Building Single-Page Applications (SPAs)React's Purpose: Building Single-Page Applications (SPAs)Apr 19, 2025 am 12:06 AM

React is the preferred tool for building single-page applications (SPAs) because it provides efficient and flexible ways to build user interfaces. 1) Component development: Split complex UI into independent and reusable parts to improve maintainability and reusability. 2) Virtual DOM: Optimize rendering performance by comparing the differences between virtual DOM and actual DOM. 3) State management: manage data flow through state and attributes to ensure data consistency and predictability.

React: The Power of a JavaScript Library for Web DevelopmentReact: The Power of a JavaScript Library for Web DevelopmentApr 18, 2025 am 12:25 AM

React is a JavaScript library developed by Meta for building user interfaces, with its core being component development and virtual DOM technology. 1. Component and state management: React manages state through components (functions or classes) and Hooks (such as useState), improving code reusability and maintenance. 2. Virtual DOM and performance optimization: Through virtual DOM, React efficiently updates the real DOM to improve performance. 3. Life cycle and Hooks: Hooks (such as useEffect) allow function components to manage life cycles and perform side-effect operations. 4. Usage example: From basic HelloWorld components to advanced global state management (useContext and

React's Ecosystem: Libraries, Tools, and Best PracticesReact's Ecosystem: Libraries, Tools, and Best PracticesApr 18, 2025 am 12:23 AM

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

React and Frontend Development: A Comprehensive OverviewReact and Frontend Development: A Comprehensive OverviewApr 18, 2025 am 12:23 AM

React is a JavaScript library developed by Facebook for building user interfaces. 1. It adopts componentized and virtual DOM technology to improve the efficiency and performance of UI development. 2. The core concepts of React include componentization, state management (such as useState and useEffect) and the working principle of virtual DOM. 3. In practical applications, React supports from basic component rendering to advanced asynchronous data processing. 4. Common errors such as forgetting to add key attributes or incorrect status updates can be debugged through ReactDevTools and logs. 5. Performance optimization and best practices include using React.memo, code segmentation and keeping code readable and maintaining dependability

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.