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月前
|
关系型数据库 MySQL 数据库
什么是事务以及事务的四大特性
事务是数据库操作的基本单元,具备ACID四大特性:原子性、一致性、隔离性、持久性。并发事务可能引发脏读、不可重复读、幻读等问题,数据库通过不同隔离级别(如读已提交、可重复读、串行化)加以控制。MySQL默认采用可重复读级别,在保证数据一致性的同时兼顾性能,避免高隔离级别带来的性能损耗。
|
存储 JSON NoSQL
Node.js使用数据库LevelDB:超高性能kv存储引擎
Node.js被设计用来做快速高效的网络I/O。它的事件驱动流使其成为一种智能代理的理想选择,通常作为后端系统和前端之间的粘合剂。Node的设计初衷就是为了实现这一目的,但与此同时,它已成功用于构建传统的Web应用程序:一个HTTP服务器,提供为HTML页面或JSON消息响应,并使用数据库存储数据。
1075 0
Node.js使用数据库LevelDB:超高性能kv存储引擎
|
机器学习/深度学习 数据采集 算法
时间序列结构变化分析:Python实现时间序列变化点检测
在时间序列分析和预测中,准确检测结构变化至关重要。新出现的分布模式往往会导致历史数据失去代表性,进而影响基于这些数据训练的模型的有效性。
1754 1
|
存储 负载均衡 NoSQL
搭建高可用及负载均衡的Redis
通过本文介绍的高可用及负载均衡Redis架构,可以有效提升Redis服务的可靠性和性能。主从复制、哨兵模式、Redis集群以及负载均衡技术的结合,使得Redis系统在应对高并发和数据一致性方面表现出色。这些配置和技术不仅适用于小型应用,也能够支持大规模企业级应用的需求。希望本文能够为您的Redis部署提供实用指导和参考。
870 9
|
运维 Java Linux
Linux运维工程师面试题(1)
Linux运维工程师面试题(1) 1 别名、内部命令、外部命令的执行顺序 2 linux 系统启动流程 3 忘记用户密码的方法 4 忘记 grub 密码怎么解决 5 硬盘空间满了怎么处理,怎么找到硬盘中的大文件 6 硬盘明明有很多空间,为什么无法存储文件 7 进程使用内存问题 8 进程、线程和协程的区别 9 使用 find 命令找出/data目录下15天以上以log结尾的文件并删除 10 su、su - 和 sudo 的区别
434 1
Linux运维工程师面试题(1)
|
网络协议 Unix
UDP connect 的作用
【4月更文挑战第8天】UDP的`connect`主要用来让应用接收“异步错误”信息。
|
安全 前端开发 JavaScript
防御点击劫持:X-Frame-Options头的重要性与实践
防御点击劫持:X-Frame-Options头的重要性与实践
2408 0
|
Shell 应用服务中间件 nginx
Docker命令集大全(Docker命令,一篇搞定)
【1月更文挑战第12天】 一、Docker容器命令: 二、Docker镜像命令 三、重启Docker命令 四、Docker数据卷命令 五、挂载数据卷
979 3
|
存储 NoSQL
MongoDB高可用集群配置的几种方案
高可用性即HA(High Availability)指的是通过尽量缩短因日常维护操作(计划)和突发的系统崩溃(非计划)所导致的停机时间,以提高系统和应用的可用性。
26043 0
|
编解码 算法 容器
音视频基础知识
音视频基础知识
833 0

热门文章

最新文章