您的位置:首页 > 其它

ECMAScript 2020 新增功能速成

2021-01-29 12:57 357 查看

ECMAScript 2020 新增功能速成

疯狂的技术宅 前端先锋

ECMAScript 2020 是我们最喜欢的编程语言的第 11 版,其中包含一些新功能。有些是小特性,但有些将会有可能永远改变我们编写 JavaScript 的方式。

Dynamic import()

ES2015 引入了 static import 语法。现在你可以从一个模块导出变量,然后将其导入另一个模块。

1// utils.js
2export function splitName(name) {
3  return name.split(" ");
4}
5
6// index.js
7import { splitName } from "./utils";
8
9console.log(splitName("John Snow"));

这种语法被称为静态语法,因为你无法在运行时动态导入模块(取决于某些条件)。请注意,这不一定是坏事:可以在编译时优化静态导入,并允许 Tree Shaking。

另一方面,如果合理地使用了动态导入,则可以通过按需加载依赖项来帮助减少分发包的大小。

新的 dynamic import 语法看起来像一个函数(但不是),它返回 promise,这也意味着可以将其与 async/await一起使用。

1// ...
2const mod = figure.kind === "rectangle" ? "rectangle.js" : "circle.js";
3const { calcSquare } = await import(mod);
4console.log(calcSquare(figure));

空值合并

流行的用 short-circuting 设置默认值的方法有其缺陷。由于它实际上不是在检查空值,而是在检查是否为“假”(https://developer.mozilla.org/zh-cn/docs/Glossary/Falsy),因此它会以诸如 false 或 0(两者均被视为假)。

ES2020引入了一个新的运算符 ??,该运算符的工作原理与其类似,但仅在初始值为 null 或 undefined 时才赋值为右手。

这是一个简单的例子:

1const initialVal = 0;
2
3// old way
4const myVar = initialVal || 10; // => 10
5
6// new way
7const myVar = initialVal ?? 10; // => 0

可选链

新的 optional chaining 运算符用来在处理嵌套对象并检查可能的 undefineds 时使代码更短。

1const user = { name: "John" };
2
3// Fails with `Uncaught TypeError: Cannot read property 'city' of undefined`
4const city = user.address.city;
5
6// Works but verbose
7let city = "Not Set";
8if (user.address !== undefined && user.address !== null) {
9  city = user.address.city;
10}
11
12// Works and concise but requires a 3rd party library
13const city = _.get(user, "address.city", "Not Set");
14
15//
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: