专业的编程技术博客社区

网站首页 > 博客文章 正文

种草 ES2020 八大新功能(es2020特性)

baijin 2024-09-27 06:42:49 博客文章 5 ℃ 0 评论

作者 | Thomas Guibert

译者 | 孙薇,责编 | 伍杏玲

出品 | CSDN(ID:CSDNnews)

大家都知道,自2015年发布的ES6开始,每年Ecma国际(欧洲计算机制造商协会,European Computer Manufacturers Association)第39技术委员会(TC39)都会发布新版的ECMAScript,而ECMAScript 2020则是ECMAScript语言规范的第11版。下面我们就来一探究竟。

‘globalThis’

JavaScript语言如今相当热门,也广泛应用在各种环境中——当然也会在Web浏览器中,但也可以在服务器端、智能手机上和机器人等设备上运行。

每个环境访问全局对象时,都有自己的对象模型和语法。因此,想要编写在多个环境中能够运作的JavaScript代码可能会很困难:

// browser environment
console.log(window);

// node.js environment
console.log(global);

// Service worker environment
console.log(self);// ..

当然,可以编写一个检查当前环境的函数,定制跨平台的标准化代码,但无需再这样做了。

如今,globalThis属性是跨环境以一致方式访问全局对象的标准方式。

‘Promise.allSettled’

Promise.allSettled 方法会返回一个promise,承诺在所有给定的承诺均已解决或被拒绝后负责解决,这个方法附有一组对象,分别通过status属性描述各个promise的结果,也就能更容易地过滤出来。

const p1 = new Promise((res) => res("??"));
const p2 = new Promise((res, rej) => rej("??"));
const p3 = new Promise((res) => res("??"));Promise.allSettled([p1, p2, p3]).then(data => console.log(data));
// [
// { status: "fulfilled", value: "??" },
// { status: "rejected", value: "??" },
// { status: "fulfilled", value: "??" },
// ]

空值合并运算符

当执行属性访问时尝试提供默认值,新的方法便是采用空值合并运算符。与or运算符不同,我们在两个操作数之间以 ??来代替||操作符。

比较下这两个运算符:

const test = {
: ,
number: 0,
string: '',
boolean: false
};const undefinedValue = test.dog || "Cat"; // "Cat"
const undefinedValue = test.dog ?? "Cat"; // "Cat"const Value = test. || "Default"; // "Default"
const Value2 = test. ?? "Default"; // "Default"const numberValue = test.number || 1; // 1
const numberValue2 = test.number ?? 1; // 0const stringValue = test.string || "Hello"; // "Hello"
const stringValue2 = test.string ?? "Hello"; // ""const booleanValue = test.boolean || true; // true
const booleanValue2 = test.boolean ?? true; // false

如上所示,空值合并运算符仅在 ??左侧的操作数为或undefined时,返回右侧的操作数。

类的私有字段

默认情况下,在JS中,所有内容都可以从类外部访问。这项提案提出了一种在类中声明属性的新方法,以确保该私有字段从外部无法访问。

给属性名称加上#前缀,就表示此字段是私有字段,不对外公开。下面请看示例:

class Counter {
#x = 0; increment {
this.#x++;
}

getNum{
return this.#x;
}
}const counter = new Counter;console.log(counter.#x);
// Uncaught SyntaxError: Private field '#x' must be declared in an enclosing class counter.increment; // Works
console.log(counter.getNum); // 1

可选链运算符

截至目前,在搜索某个对象内部深入嵌套的属性值时,或者使用返回对象或/undefined的API时,通常用以下方式来检查中间值:

// Checking for intermediate nodes:
const deeplyNestedValue = obj && obj.prop1 && obj.prop1.prop2;// Checking if the node exists in the DOM:
const fooInputEl = document.querySelector('input[name=foo]');
const fooValue = fooInputEl && fooInputEl.value;

可选链运算符则允许我们更简单地处理许多情况。重写上面的示例将获得以下代码:

// Checking for intermediate nodes:
const deeplyNestedValue = obj?.prop1?.prop2;// Checking if the node exists in the DOM:
const fooValue = document.querySelector('input[name=foo]')?.value;

可选链运算符是一个短路计算操作,即当左侧?.检查到或undefined时,就会停止表达式的运行:

// x is incremented if and only if 'a' is not  or undefined
a?.[++x]

可选链可与函数一并使用:

func?.(...args) // optional function or method call

‘BigInt’

我们已经用Number来表示JS中的数字,问题在于最大的数字是2?3,再往上的数字就不可靠了。

const x = Number.MAX_SAFE_INTEGER; // 9007199254740991
const y = x + 1; // 9007199254740992 ? equal to 2^53
const z = x + 2; // 9007199254740992 ? well, it's broken

BigInt提供了一种方法,来表示大于2?3的数字。通过在整数末尾添加n来创建:

const aBigInteger = 9007199254740993n;
// There is also a constructor:
const evenBigger = BigInt(9007199254740994); // 9007199254740994n
const fromString = BigInt("9007199254740995"); // 9007199254740995n

BigInt通常的操作与数字相同,但不能在运算中一同使用:

let sum = 1n + 2, multiplication = 1n * 2;
// TypeError: Cannot mix BigInt and other types, use explicit conversions

可使用构造函数Number将BigInt转化为Number,但在某些情况下可能会失去精度。因此,建议仅在代码中相应预期数值较大时再使用BigInt。

Number(900719925474099267n); // 900719925474099300 ? ???♂?

动态import

目前从./module导入模块的形式是静态的,只接受字符串文字,也仅作为链接过程在运行前起效。

动态的 import(...)允许开发者在运行时动态载入部分JS应用,相对于目前的导入方式有着一系列优势:

  • 加载用户语言,而不是全部加载

  • 延迟加载应用程序的路径,从而提高性能

  • 找不到模块的情况下也能处理故障

运行方式:

// Used as a function, import returns a promise that can be handled the 2 usuals ways:// Using callback
import('/module.js')
.then((module) => {
// Do something with the module.
});// Using async / await
async function {
let module = await import('/modules.js');
}

下面是一些值得注意的区别,与通常的导入声明不同:

  • import 可在脚本中使用,而不仅是模块中;

  • import 可以在任何级别任何位置运行,而且不会被挂起;

  • import 可以接受任意字符串(需具有运行时确定的模板字符串,如下所示),而不仅是静态字符串文字。

‘String.protype.matchAll’

matchAll 方法会检索字符串是否匹配给定的正则表达式(RegExp),并返回所有结果的迭代程序,以如下方式运行:

const regexp = RegExp('[a-z]*ball','g');
const str = 'basketball handball pingpong football';
const matches = str.matchAll(regexp);// Since it is an iterator, you can loop trought results this way:
let match = matches.next;
while (!match.done) {
console.log(match.value);
match = matches.next;
}
// ["basketball", index: 0, input: "basketb...", groups: undefined]
// ["handball", index: 11, input: "basketb...", groups: undefined]
// ["football", index: 29, input: "basketb...", groups: undefined]// One can also get an array of all results
let results = [...str.matchAll(regexp)];

在与全局/g标志一同使用时,match方法不返回捕获组,请使用matchAll。

以上是今年的全部新功能。Babel已经拥有上述几乎所有功能的插件,如果想要在项目中使用,可以参考如下:

@babel/plugin-proposal-ish-coalescing-operator

@babel/plugin-proposal-private-methods

@babel/plugin-proposal-optional-chaining

@babel/plugin-syntax-bigint

@babel/plugin-syntax-dynamic-import

原文链接:https://medium.com/better-programming/8-new-features-shipping-with-es2020-7a2721f710fb

本文为 CSDN 翻译,转载请注明来源出处。

?知识图谱够火,但底层技术环节还差点火候|AI技术生态论

?深度|一文读懂“情感计算”在零售中的应用发展

?三大运营商将上线5G消息;苹果谷歌联手,追踪30亿用户;jQuery 3.5.0发布|极客头条

?曾遭周鸿祎全网封杀的360猛将:草根打工到36岁身家上亿的逆袭!

?你公司的虚拟机还闲着?基于Jenkins和Kubernetes的持续集成测试实践了解一下!

?从Web1.0到Web3.0:详析这些年互联网的发展及未来方向

?一文读懂“情感计算”在零售中的应用发展

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表