ecmascript_ECMAScript 2020(ES2020)的新增功能

ecmascript

It’s time for yet another update on the ever-changing work of art that is JavaScript. In this article, we’re going to review some of the latest and greatest features coming with ES2020.

现在是时候对JavaScript不断变化的艺术品进行另一次更新了。 在本文中,我们将回顾ES2020随附的一些最新和最出色的功能。

安装 (Installation)

Since many people don’t think to update their browsers to make their developer’s lives easier, we’ll need to use babel to get started using features that are not available across the board for users. For simplicity’s sake, I’ll use the Parcel bundler to get everything running as quickly as possible.

由于许多人不希望更新浏览器来简化开发人员的生活,因此我们需要使用babel来开始使用用户无法全面使用的功能。 为简单起见,我将使用Parcel捆绑器使所有内容尽快运行。

$ yarn add parcel-bundler
package.json
package.json
"scripts": {
  "start": "parcel index.html"
},

Sadly, at the time of this writing we’re too far ahead of our time and there doesn’t seem to be a working preset for ES2020. If you throw these in a .babelrc file and save, Parcel should handle installing everything for you.

可悲的是,在撰写本文时,我们已经领先于我们的时代了,似乎还没有ES2020的有效预设。 如果将它们放在.babelrc文件中并保存,Parcel应该会为您安装所有内容。

.babelrc
.babelrc
{
  "plugins": [
    "@babel/plugin-proposal-nullish-coalescing-operator",
    "@babel/plugin-proposal-optional-chaining",
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-proposal-private-methods",
    "@babel/plugin-syntax-bigint"
  ]
}

私有类变量 (Private Class Variables)

One of the main purposes of classes is to contain our code into more reusable modules. Because you’ll create a class that’s used in many different places you may not want everything inside it to be available globally.

类的主要目的之一是将我们的代码包含在可重用的模块中。 因为您将创建一个在许多不同地方使用的类,所以您可能不希望其中的所有内容在全局范围内都可用。

Now, by adding a simple hash symbol in front of our variable or function we can reserve them entirely for internal use inside the class.

现在,通过在变量或函数前面添加一个简单的哈希符号,我们可以将它们完全保留给类内部使用。

class Message {
  #message = "Howdy"

  greet() { console.log(this.#message) }
}

const greeting = new Message()

greeting.greet() // Howdy
console.log(greeting.#message) // Private name #message is not defined

承诺全部解决 (Promise.allSettled)

When we’re working with multiple promises, especially when they are reliant on each other, it could be useful to log what’s happening to each to debug errors. With Promise.allSettled, we can create a new promise that only returns when all of the promises passed to it are complete. This will give us access to an array with some data on each promise.

当我们使用多个promise时,尤其是当它们相互依赖时,记录每个事件的发生以调试错误可能很有用。 使用Promise.allSettled ,我们可以创建一个新的promise,仅当传递给它的所有promise都完成时才返回。 这将使我们能够访问一个数组,其中包含每个promise的一些数据。

const p1 = new Promise((res, rej) => setTimeout(res, 1000));

const p2 = new Promise((res, rej) => setTimeout(rej, 1000));

Promise.allSettled([p1, p2]).then(data => console.log(data));

// [
//   Object { status: "fulfilled", value: undefined},
//   Object { status: "rejected", reason: undefined}
// ]

空位合并运算符 (Nullish Coalescing Operator)

Because JavaScript is dynamically typed, you’ll need to keep JavaScript’s treatment of truthy/falsy values in mind when assigning variables. If we have a object with some values, sometimes we want to allow for values that are technically falsy, like an empty string or the number 0. Setting default values quickly gets annoying since it’ll override what should be valid values.

由于JavaScript是动态类型的,因此在分配变量时,您需要牢记JavaScript对真实/错误值的处理。 如果我们有一个带有某些值的对象,有时我们希望允许使用在技术上是虚假的值,例如空字符串或数字0。设置默认值很快会很烦人,因为它将覆盖应为有效值的内容。

let person = {
  profile: {
    name: "",
    age: 0
  }
};

console.log(person.profile.name || "Anonymous"); // Anonymous
console.log(person.profile.age || 18); // 18

Instead of double pipes we can use the double question marks operator to be a bit more type strict, which only allows the default when the value is null or undefined.

代替双管道,我们可以使用双问号运算符将类型更严格一些,仅当值为null或未定义时才允许使用默认值。

console.log(person.profile.name ?? "Anonymous"); // ""
console.log(person.profile.age ?? 18); // 0

可选链接运算符 (Optional Chaining Operator)

Similar to the nullish coalescing operator, JavaScript may not act how we want when dealing with falsy values. We can return a value if what we want is undefined, but what if the path to it is undefined?

与无效的合并运算符相似,JavaScript处理虚假值时可能无法按照我们的意愿行事。 如果我们想要的是不确定的,我们可以返回一个值,但是如果它的路径是不确定的,该怎么办?

By adding a question mark before our dot notation we can make any part of a value’s path optional so we can still interact with it.

通过在点符号前添加问号,我们可以将值路径的任何部分设为可选,以便我们仍然可以与之交互。

let person = {};

console.log(person.profile.name ?? "Anonymous"); // person.profile is undefined
console.log(person?.profile?.name ?? "Anonymous");
console.log(person?.profile?.age ?? 18);

You can refer to this post to learn more about Optional Chaining and Nullish Coalescing.

您可以参考这篇文章,以了解有关可选链和空位合并的更多信息。

大整数 (BigInt)

We won’t go into the technical details, but because of how JavaScript handles numbers, when you go high enough things start to get a bit wonky. The largest number JavaScript can handle is 2^53, which we can see with MAX_SAFE_INTEGER.

我们不会讨论技术细节,但是由于JavaScript处理数字的方式,当您提高数字时,事情会变得有些古怪。 JavaScript可以处理的最大数目是2 ^ 53,可以通过MAX_SAFE_INTEGER看到。

const max = Number.MAX_SAFE_INTEGER;

console.log(max); // 9007199254740991

Anything above that and things start to get a little weird…

超过此限制,一切开始变得有点奇怪…

console.log(max + 1); // 9007199254740992
console.log(max + 2); // 9007199254740992
console.log(max + 3); // 9007199254740994
console.log(Math.pow(2, 53) == Math.pow(2, 53) + 1); // true

We can get around this with the new BigInt datatype. By throwing the letter ’n’ on the end we can start using and interacting with insanely large numbers. We’re not able to intermix standard numbers with BigInt numbers, so any math will need to be also done with BigInts.

我们可以使用新的BigInt数据类型解决此问题。 通过在末尾加上字母“ n ”,我们可以开始使用疯狂的数字并与之交互。 我们无法将标准数字与BigInt数字混合使用,因此任何数学运算都需要使用BigInts完成。

const bigNum = 100000000000000000000000000000n;

console.log(bigNum * 2n); // 200000000000000000000000000000n

动态导入 (Dynamic Import)

If you had a file full of utility functions, some of them may rarely be used and importing all of their dependencies could just be a waste of resources. Now we can use async/await to dynamically import our dependencies when we need them.

如果您有一个充满实用程序功能的文件,则其中的某些实用程序可能很少使用,而导入其所有依赖项可能只是浪费资源。 现在,我们可以在需要时使用async / await动态导入依赖项。

This will not work with our current Parcel setup, since we’re using imports which will only work in a Node.js environment.

这不适用于我们当前的Parcel设置,因为我们使用的导入仅在Node.js环境中有效。

math.js
math.js
const add = (num1, num2) => num1 + num2;

export { add };
index.js
index.js
const doMath = async (num1, num2) => {
  if (num1 && num2) {
    const math = await import('./math.js');
    console.log(math.add(5, 10));
  };
};

doMath(4, 2);

结论 (Conclusion)

Now you’re ready to start amazing or perhaps confusing your coworkers with JavaScript features that aren’t even in most browsers, yet (unless they are if you are reading this from the future 😉).

现在,您可以开始惊艳您的同事,或者将您的同事与大多数浏览器中都没有JavaScript功能混淆(除非您从将来开始阅读reading,除非您这样做)。

翻译自: https://www.digitalocean.com/community/tutorials/js-es2020

ecmascript

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值