ECMAScript 2022(ES13)初体验

简介: 2022 年 6 月 22 日,第 123 届 ECMA 大会批准了 ECMAScript 2022 语言规范,这意味着它现在正式成为标准。下面就来看看 ECMAScript 2022 有哪些新特性!

ECMAScript2022ES13

2022622123ECMAECMAScript2022ECMAScript2022

640.png


  • Top-levelAwait
  • Object.hasOwn()
  • at()
  • error.cause


  • ES14Array.prototype.findLastArray.prototype.findLastIndex

Top-levelAwaitawait

asyncawaitES2017ES8Promiseawaitasync使使awaitUncaughtSyntaxError:awaitisonlyvalidinasyncfunctionsandthetoplevelbodiesofmodules

awaitpromise.jsjs

// promise.js
let res = { name: "" },
  num;
const np = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(456);
    }, 100);
  });
};
const p = async () => {
  const res1 = await np();
  res.name = res1;
  num = res1;
};
p();
export default res;
//validate.js
import res from "./p.js";
console.log("res", res, num);
// 这时 res 和 num 都是 undefined

resnum访

setTimeout(() => {
 console.log("res3000", res, num);
}, 1000);
// res 可以正确输出 {name: 456}
// num 还是 undefined

resnum

res100resp.jsresnump.jsundefined使await

// p.js
let res = { name: "" },
  num;
const np = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(456);
    }, 100);
  });
};
// 这里进行改造
const res1 = await np();
res.name = res1;
num = res1;
export { res, num };
//validate.js
import { res, num } from "./p.js";
console.log("res adn num", res, num);
// 全部正常输出

awaitnp

await使

  • js(js)
  • 退
let depVersion;
try {
  depVersion = await import(xxx/depVersion-2.0.0.min.js)
}catch {
  depVersion = await import(xxx/depVersion-1.5.0.min.js)
}

let myModule = 'await-module'
const module = await import(`./${myModule}`)

640 (1).png

Object.hasOwn()

ES5使

object = {firstName: '四', lastName: '李'}
for (const key in object) {
  if (Object.hasOwnProperty.call(object, key)) {
    const element = object[key];
    console.log(element)
  }
}

ES6Object.hasOwn

object = {firstName: '四', lastName: '李'}
for (const key in object) {
  if (Object.hasOwn(object, key)) {
    const element = object[key];
    console.log(element)
  }
}

640 (2).png

at()

TC39ArrayStringTypedArray.at()

ES13访arr[arr.length-N]使arr.slice(-N)[0]

ES13使at()

// 数组
const array = [0,1,2,3,4,5];
array.at(-1) // 5
array.at(-2) // 4
// 字符串
string= 'abcdefg'
string.at(-2) // f

640 (3).png

ErrorCause

// ES13 之前通常用以下几种方式处理错误
async function errFunc() {
  const rawResource = await axios('/testError')
    .catch(err => {
      // 第一种
      throw new Error('我的错误信息:', err.message);
      // 第二种,需要连接错误信息
      const wrapErr = new Error('Download raw resource failed');
      // 自己创建 一个 cause 属性来接收错误上下文
      wrapErr.cause = '错误原因:' + err;
      throw wrapErr;
      // 第三种,需要连接错误信息
      class CustomError extends Error {
         constructor(msg, cause) {
           super(msg);
            // 自己创建 一个 cause 属性来接收错误上下文
           this.cause = cause;
         }
       }
       throw new CustomError('Download raw resource failed', err);
    });
}
try {
    const res = await errFunc()
}catch (err) {
    console.log(err)
    console.log(err.cause)
}
// 第一种输出:Uncaught Error: 我的错误信息:Failed to fetch
// 第一种输出:undefined
// 第二种输出:Uncaught Error: 我的错误信息
 // 第二种输出:错误原因: err
// 第三种:Uncaught Error: 我的错误信息
// 第三种输出:错误原因: err

d/dm1.indices

// ?<m>n:命名分组,m 为组名称,n 为正则表达式
const re1 = /a+(?<Z>z)?/d;
// indices are relative to start of the input string:
const s1 = "xaaaz";
const m1 = re1.exec(s1);
console.log(m1.indices)

640 (4).png

class

ES13

class myClass {
  constructor() {
    this.count = 1
    this.increment = this.increment.bind(this);
  }
  increment() {
    this.count += 1
  }
}

ES13使使

class myClass {
  count = 1
  increment = () => {
    this.count += 1
  }
}

classclass

class myClass {
  count = 1
  setCount = () => {
    this.count += 1
  }
}
const es13 = new myClass()
es13.count = 5
// myClass {count: 5, setCount: ƒ}count: 5setCount: () => {     this.count += 1   }[[Prototype]]: Object

countsetCount使##

class myClass {
  #count = 1
  setCount = () => {
    this.#count += 1
  }
}
const es13 = new myClass()
es13.setCount() // 正常修改,每执行执行一次 setCount 方法后 #count的值每一次都加1
// 直接修改私有属性
es13.#count = 5
// 报错:Uncaught SyntaxError: Private field '#count' must be declared in an enclosing class

UncaughtSyntaxError:Privatefield'#count'mustbedeclaredinanenclosingclass

#

class myClass {
  #count = 1
  #setCount = () => {
    this.#count += 1
  }
    newSetCount = () => {
    this.#setCount()
  }
}
const es13 = new myClass()
es13.#setCount() 
// 直接调用私有方法报错:Uncaught SyntaxError: Private field '#setCount' must be declared in an enclosing class
//通过公共方法 newSetCount 调用
es13.newSetCount() 
//成功,#count + 1

使#

class myClass {
 //静态公共字段
 static color = 'blue'
 // 静态私有字段
 static #count = 1
 // 静态私有方法
 static #setCount = () => {
    this.#count += 1
  }
  newSetCount = () => {
    this.#setCount()
  }
}
const es13 = new myClass()
实例 es13 上面只有 newSetCount() 方法
es13.newSetCount() 
// 报错:Uncaught SyntaxError: Private field '#setCount' must be declared in an enclosing class

访使this,

class myClass {
// 静态私有字段
 static #count = 1
 // 静态私有方法
 static #setCount = () => {
   // 实例化之后,this 不再指向 myClass,所有需要改成 myClass 类调用
    myClass.#count += 1
  }
  newSetCount = () => {
    // 实例化之后,this 不再指向 myClass,所有需要改成 myClass 类调用
    myClass.#setCount()
  }
}
const es13 = new myClass()
es13.newSetCount() 
// 成功

trycatch/访

ES13

class Person {
    static EEEOR = "error"
    static SUCCESS_TYPE = "success_type";
    constructor() {
        // ...
    }
    try {
        // ...
    } catch {
        // ...
    }
}

UncaughtSyntaxError:Unexpectedtoken'{'

ES13:try...cathc使static

class Person {
    static EEEOR = "error"
    static SUCCESS_TYPE = "success_type";
    constructor() {
        // ...
    }
    static {
      try {
        // ...
      } catch {
        // ...
      }
    }
}

ES14

  • Array.prototype.findLast
  • Array.prototype.findLastIndex

Tips

  • Array.prototype.findLastArray.prototype.find
  • Array.prototype.findLastIndexArray.prototype.findIndex

Array.prototype.findLastArray.prototype.findLastIndex

Array.prototype.findArray.prototype.findIndex

const array = [{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }];
array.find(n => n.value % 2 === 1); // { value: 1 }
array.findIndex(n => n.value % 2 === 1); // 0
// ======== Before the proposal =========== 
// find
[...array].reverse().find(n => n.value % 2 === 1); // { value: 3 }
// findIndex
array.length - 1 - [...array].reverse().findIndex(n => n.value % 2 === 1); // 2
array.length - 1 - [...array].reverse().findIndex(n => n.value === 42); // should be -1, but 4
// ======== In the proposal =========== 
// find
array.findLast(n => n.value % 2 === 1); // { value: 3 }
// findIndex
array.findLastIndex(n => n.value % 2 === 1); // 2
array.findLastIndex(n => n.value === 42);

0 (1).png

相关文章
|
2月前
|
JSON 前端开发 JavaScript
掌握现代JavaScript:ES7到ES12的新特性全解析!
ES2016(ES7)中新增了如下特性👇 Array.prototype.includes Exponentiation Operator
|
7月前
|
存储 JavaScript 前端开发
ECMAScript 2020(ES11)新特性简介
ECMAScript 2020(ES11)新特性简介
63 0
|
7月前
|
JavaScript 前端开发 索引
ECMA 2022 (es13) 新特性
ECMA 2022 (es13) 新特性
36 0
|
8月前
|
前端开发 JavaScript Java
【编程指南】ES2016到ES2023新特性解析一网打尽(二)
【编程指南】ES2016到ES2023新特性解析一网打尽(二)
119 0
|
8月前
|
JSON JavaScript 前端开发
【编程指南】ES2016到ES2023新特性解析一网打尽(一)
【编程指南】ES2016到ES2023新特性解析一网打尽(一)
70 0
|
前端开发 JavaScript Java
11 个 ES2022(ES13)中惊人的 JavaScript 新特性
与许多其他编程语言一样,JavaScript 也在不断发展,每年,该语言都会通过新功能变得更强大,让开发人员编写更具表现力和简洁的代码。
11 个 ES2022(ES13)中惊人的 JavaScript 新特性
|
前端开发 JavaScript Java
ECMAScript 2021(ES12)新特性简介
ECMAScript 2021(ES12)新特性简介
|
存储 XML JSON
ECMAScript 2019(ES10)新特性简介
ECMAScript 2019(ES10)新特性简介
|
JavaScript 前端开发 Java
ECMAScript 2018(ES9)新特性简介
ECMAScript 2018(ES9)新特性简介
|
存储 前端开发 JavaScript
ECMAScript 2017(ES8)新特性简介
ECMAScript 2017(ES8)新特性简介