ES2020:新功能和示例摘要🔥🤠入门🤖ES2020 功能

2025-06-07

ES2020:新功能和示例摘要🔥

🤠 入门

🤖 ES2020 功能

在本文中,我们将回顾 ES2020 的一些最新、最强大的功能。🔥

🤠 入门

我们将使用 Babel 在 Node.js 环境中测试这些功能。

方法 1:从头开始创建项目

首先创建一个新项目:

$ mkdir es2020-tests
$ yarn init

现在添加@babel/cli @babel/core @babel/node @babel/preset-env依赖项:

$ yarn add --dev @babel/cli @babel/core @babel/node @babel/preset-env

创建.babelrc文件:

{
    "presets": ["@babel/preset-env"]
}

方法二:克隆源代码库

您还可以克隆以下GitHub存储库,其中包含本文中示例的设置和源代码。

$ git clone git@github.com:olivierloverde/es2020-examples.git
$ yarn install

🤖 ES2020 功能

类中的私有变量

现在,您可以使用 hastag 在类中声明私有变量#。如果在类外部调用私有变量,则会抛出SyntaxError

class MyClass {
    #privateVariable = "Hello private world"

    helloWorld() { console.info(this.#privateVariable) }
}

const myClass = new MyClass()
myClass.helloWorld() // works
console.info(myClass.#privateVariable) // SyntaxError: Private field '#privateVariable' must be declared in an enclosing class

GitHub 上的源代码

BigInt

由于 Javascript 内部表示数字的方式,对最大整数存在限制(它使用 64 位浮点数,参见IEE 754)。

const maxInteger = Number.MAX_SAFE_INTEGER;

console.info(maxInteger); // 9007199254740991
console.info(maxInteger + 1); // 9007199254740992
console.info(maxInteger + 2); // 9007199254740992 ??
console.info(maxInteger + 3); // 9007199254740994
console.info(maxInteger + 200); // 9007199254741192 ??
console.info(maxInteger * 200); // 1801439850948198100 ??

GitHub 上的源代码

现在有一个原生解决方案,BigInt 是一个内置对象,它提供了一种表示大于 2⁵³ 的整数的方法——1,这是 JS 数字中最大的数字。

您可以通过以下方式创建 BigInt:

  • 创建BigInt对象:const value = BigInt(500)
  • 将 a 附加n到数字:const value = 500n

目前,它不能与内置Math对象中的方法一起使用,也不能与 一起操作。由于所有 BigInt 都是有符号的,Number因此支持按位运算符。>>>

// Using BigInt
const maxIntegerBigInt = BigInt(maxInteger);
console.info(maxIntegerBigInt); // 9007199254740991n
console.info(maxIntegerBigInt + 1n); // 9007199254740992n
console.info(maxIntegerBigInt + 2n); // 9007199254740993n 
console.info(maxIntegerBigInt + 3n); // 9007199254740994n 
console.info(maxIntegerBigInt + 200n); // 9007199254741191n
console.info(maxIntegerBigInt * 200n); // 1801439850948198200n

GitHub 上的源代码

Promise.allSettled()

Promise.allSettled 以对象数组Promise作为参数,并等待所有承诺都解决后以对象数组的形式返回相应的结果{status, ?value, ?reason}

const resolvingPromise1000ms = new Promise((resolve, reject) => setTimeout(resolve, 1000));
const rejectingPromise2000ms = new Promise((resolve, reject) => setTimeout(reject, 2000));

const timeCheckpoint = Date.now();
Promise.allSettled([
    resolvingPromise1000ms, 
    rejectingPromise2000ms
]).then(data => {
    const elapsedTimeInMS = Date.now() - timeCheckpoint;
    console.info(`Promise.allSettled resolved after ${elapsedTimeInMS}ms`)
    console.info(data)
});

/*
Promise.allSettled resolved after 2006ms // ? not sure why we have 6ms
[
  { status: 'fulfilled', value: undefined },
  { status: 'rejected', reason: undefined }
]
*/

GitHub 上的源代码

空值合并运算符

使用||运算符时,它会返回第一个参数true。但是,有时你会将默认值视为false0""为了避免这种情况,我们可以使用空值合并运算符,??如下所示:

let object = {
    car: {
        speed: 0,
        name: ""
    }
};

console.info(object.car.speed || 90); // 90
console.info(object.car.speed ?? 90); // 0

console.info(null || true); // true
console.info(null ?? true); // true

console.info(undefined || true); // true
console.info(undefined ?? true); // true

console.info(0 || true); // true
console.info(0 ?? true); // 0

console.info("" || true); // true
console.info("" ?? true); // ""

console.info([] || true); // []
console.info([] ?? true); // []

console.info({} || true); // {}
console.info({} ?? true); // {}

console.info(true || "hey"); // true
console.info(true ?? "hey"); // true

console.info(false || true); // true
console.info(false ?? true); // false

GitHub 上的源代码

可选链接运算符

我们以下面的对象为例:

let person = {
    name: "John",
    age: 20
};

假设我们想要访问这个对象上我们不确定是否拥有的属性,我们通常会这样做:

if (person.city !== undefined &&  person.city.locale !== undefined) {
    const cityLocale =  person.city.locale;
}

这确保程序不会抛出任何“无法读取未定义的属性名称的错误”。

现在有了可选链运算符,我们可以更简洁:

console.info(person?.city?.locale);

GitHub 上的源代码

动态导入

Dynamic 函数import()返回一个用于请求模块的模块命名空间对象的 promise。因此,我们现在可以使用import()带有await关键字的函数,并将模块命名空间对象动态地赋值给一个变量。

const print = (value) => console.info(value);

export { print };

GitHub 上的源代码

const doPrint = async (value) => {
    const Print = await import('./print.js');

    Print.print(value)
};

doPrint('Dynamic import works !');

GitHub 上的源代码

字符串.prototype.matchAll

String.prototype.match给出字符串和正则表达式之间所有匹配的数组。

例如:

const re = /(Mister )\w+/g;
const str = 'Mister Smith with Mister Galladon';
const matches = str.matchAll(re);

console.info(matches); // Object [RegExp String Iterator] {}
console.info(Array.from(matches));
/*
[
  [
    'Mister Smith',
    'Mister ',
    index: 0,
    input: 'Mister Smith with Mister Galladon',
    groups: undefined
  ],
  [
    'Mister Galladon',
    'Mister ',
    index: 18,
    input: 'Mister Smith with Mister Galladon',
    groups: undefined
  ]
]
*/

GitHub 上的源代码


现在,您就可以使用这些 ES2020 的新功能了!如果您喜欢,请给我留言!🙌


本文最初发布在我的博客olivier.codes上- https://olivier.codes/2020/04/12/ES2020-Summary-of-new-features-with-examples/

文章来源:https://dev.to/olivierloverde/es2020-summary-of-new-features-examples-2260
PREV
Shell 编程
NEXT
布局组件以及为什么我们在 React 中使用它