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" ]
}

方法2:克隆源代码存储库

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

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

2020 ES2020功能

类中的私有变量

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

class MyClass  {
    #privateVariable = "Hello private world"

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

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

来源GitHub

大整数

由于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×3 — 1(是JS编号中最大的数字)的整数的方法。

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

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

目前,它不能与内置“ Math”对象中的方法一起使用,也不能与“ Number”一起使用。 由于所有BigInts均已签名,因此除“ >>>”外,均支持按位运算符。

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

来源GitHub

Promise.allSettled()

Promise.allSettled将Promise对象数组作为参数,并等待所有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 。 但是,有时您会将默认值视为false例如0"" 。 为了避免这种情况,我们可以使用无效的合并运算符?? 如下所示:

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

动态导入

动态的import()返回所请求模块的模块名称空间对象的承诺。 因此,我们现在可以将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

String.prototype.matchAll

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

例如:

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

doPrint( 'Dynamic import works !' );

来源GitHub

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

本文最初发布在我的博客olivier.codes上

From: https://hackernoon.com/es2020-summary-of-new-features-with-examples-3u5r3yqg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值