javascript更新到了es13了。2022年6月22日,第123届ecma大会批准了ecmascript2022语言规范,这意味着它现在正式成为javascript标准;而ecmascript2022是第13次迭代,因此也可称为ecmascript13,简称es13。
本教程操作环境:windows7系统、ecmascript 13版、dell g3电脑。
新的 es13 规范终于发布了。
javascript 不是一种开源语言,它是一种需要遵循 ecmascript 标准规范编写的语言,tc39 委员会负责讨论和批准新功能的发布, 那tc39他们是谁?
“ecma international 的 tc39 是一群 javascript 开发人员、实施者、学者等,他们与社区合作维护和发展 javascript 的定义。” — tc39.es
他们的发布过程由五个阶段组成,自 2015 年以来,他们一直在进行年度发布,它们通常发生在春天举行发布。
2022 年 6 月 22 日,第 123 届 ecma 大会批准了 ecmascript 2022 语言规范,这意味着它现在正式成为标准。
有两种方法可以引用任何 ecmascript 版本:
按年份:这个新版本将是 es2022。
按其迭代次数:这个新版本将是第 13 次迭代,所以它可以被称为 es13。
那么这次这个版本有什么新东西呢?我们可以对哪些功能感到兴奋?
01、正则表达式匹配索引
目前,在 javascript 中使用 javascript regex api 时,仅返回匹配的开始索引。但是,对于一些特殊的高级场景,这还不够。
作为这些规范的一部分,添加了一个特殊的标志 d。通过使用它,正则表达式 api 将返回一个二维数组作为名索引的键。它包含每个匹配项的开始和结束索引。如果在正则表达式中捕获了任何命名组,它将在 indices.groups 对象中返回它们的开始/结束索引, 命名的组名将是它的键。
// ✅ a regex with a 'b' named group captureconst expr = /a+(?<b>b+)+c/d;const result = expr.exec("aaabbbc")// ✅ shows start-end matches + named group matchconsole.log(result.indices);// prints [array(2), array(2), groups: {…}]// ✅ showing the named 'b' group matchconsole.log(result.indices.groups['b'])// prints [3, 6]
查看原始提案,https://github.com/tc39/proposal-regexp-match-indices
02、top-level await
在此提案之前,不接受top-level await,但有一些变通方法可以模拟这种行为,但其有缺点。
top-level await 特性让我们依靠模块来处理这些 promise。这是一个直观的功能。
但是请注意,它可能会改变模块的执行顺序, 如果一个模块依赖于另一个具有top-level await 调用的模块,则该模块的执行将暂停,直到 promise 完成。
让我们看一个例子:
// users.jsexport const users = await fetch('/users/lists');// usage.jsimport { users } from "./users.js";// ✅ the module will wait for users to be fullfilled prior to executing any codeconsole.log(users);
在上面的示例中,引擎将等待用户完成操作,然后,再执行 usage.js 模块上的代码。
总之,这是一个很好且直观的功能,需要小心使用,我们不要滥用它。
在此处查看原始提案。https://github.com/tc39/proposal-top-level-await
03、.at( )
长期以来,一直有人要求 javascript 提供类似 python 的数组负索引访问器。而不是做 array[array.length-1] 来做简单的 array[-1]。这是不可能的,因为 [] 符号也用于 javascript 中的对象。
被接受的提案采取了更实际的方法。array 对象现在将有一个方法来模拟上述行为。
const array = [1,2,3,4,5,6]// ✅ when used with positive index it is equal to [index]array.at(0) // 1array[0] // 1// ✅ when used with negative index it mimicks the python behaviourarray.at(-1) // 6array.at(-2) // 5array.at(-4) // 3
查看原始提案,https://github.com/tc39/proposal-relative-indexing-method
顺便说一句,既然我们在谈论数组,你知道你可以解构数组位置吗?
const array = [1,2,3,4,5,6];// ✅ different ways of accessing the third positionconst {3: third} = array; // third = 4array.at(3) // 4array[3] // 4
04、可访问的 object.prototype.hasownproperty
以下只是一个很好的简化, 已经有了 hasownproperty。但是,它需要在我们想要执行的查找实例中调用。因此,许多开发人员最终会这样做是很常见的:
const x = { foo: "bar" };// ✅ grabbing the hasownproperty function from prototypeconst hasownproperty = object.prototype.hasownproperty// ✅ executing it with the x contextif (hasownproperty.call(x, "foo")) { ...}
通过这些新规范,一个 hasown 方法被添加到 object 原型中,现在,我们可以简单地做:
const x = { foo: "bar" };// ✅ using the new object methodif (object.hasown(x, "foo")) { ...}
查看原始提案,https://github.com/tc39/proposal-accessible-object-hasownproperty
05、error cause
错误帮助我们识别应用程序的意外行为并做出反应,然而,理解深层嵌套错误的根本原因,正确处理它们可能会变得具有挑战性,在捕获和重新抛出它们时,我们会丢失堆栈跟踪信息。
没有关于如何处理的明确协议,考虑到任何错误处理,我们至少有 3 个选择:
async function fetchuserpreferences() { try { const users = await fetch('//user/preferences') .catch(err => { // what is the best way to wrap the error? // 1. throw new error('failed to fetch preferences ' + err.message); // 2. const wraperr = new error('failed to fetch preferences'); // wraperr.cause = err; // throw wraperr; // 3. class customerror extends error { // constructor(msg, cause) { // super(msg); // this.cause = cause; // } // } // throw new customerror('failed to fetch preferences', err); }) }}fetchuserpreferences();
作为这些新规范的一部分,我们可以构造一个新错误并保留获取的错误的引用。 我们只需将对象 {cause: err} 传递给 errorconstructor。
这一切都变得更简单、标准且易于理解深度嵌套的错误, 让我们看一个例子:
async function fetcuserpreferences() { try { const users = await fetch('//user/preferences') .catch(err => { throw new error('failed to fetch user preferences, {cause: err}); }) }}fetcuserpreferences();
了解有关该提案的更多信息,https://github.com/tc39/proposal-error-cause
06、class fields
在此版本之前,没有适当的方法来创建私有字段, 通过使用提升有一些方法可以解决它,但它不是一个适当的私有字段。 但现在很简单, 我们只需要将 # 字符添加到我们的变量声明中。
class foo { #iteration = 0; increment() { this.#iteration++; } logiteration() { console.log(this.#iteration); }}const x = new foo();// ❌ uncaught syntaxerror: private field '#iteration' must be declared in an enclosing classx.#iteration// ✅ worksx.increment();// ✅ worksx.logiteration();
拥有私有字段意味着我们拥有强大的封装边界, 无法从外部访问类变量,这表明 class 关键字不再只是糖语法。
我们还可以创建私有方法:
class foo { #iteration = 0; #auditincrement() { console.log('auditing'); } increment() { this.#iteration++; this.#auditincrement(); }}const x = new foo();// ❌ uncaught syntaxerror: private field '#auditincrement' must be declared in an enclosing classx.#auditincrement// ✅ worksx.increment();
该功能与私有类的类静态块和人体工程学检查有关,我们将在接下来的内容中看到。
了解有关该提案的更多信息,https://github.com/tc39/proposal-class-fields
07、class static block
作为新规范的一部分,我们现在可以在任何类中包含静态块,它们将只运行一次,并且是装饰或执行类静态端的某些字段初始化的好方法。
我们不限于使用一个块,我们可以拥有尽可能多的块。
// ✅ will output 'one two three'class a { static { console.log('one'); } static { console.log('two'); } static { console.log('three'); }}
他们有一个不错的奖金,他们获得对私有字段的特权访问, 你可以用它们来做一些有趣的模式。
let getprivatefield;class a { #privatefield; constructor(x) { this.#privatefield = x; } static { // ✅ it can access any private field getprivatefield = (a) => a.#privatefield; }}const a = new a('foo');// ✅ works, foo is printedconsole.log(getprivatefield(a));
如果我们尝试从实例对象的外部范围访问该私有变量,我们将得到无法从类未声明它的对象中读取私有成员#privatefield。
了解有关该提案的更多信息,https://github.com/tc39/proposal-class-static-block
08、private fields
新的私有字段是一个很棒的功能,但是,在某些静态方法中检查字段是否为私有可能会变得很方便。
尝试在类范围之外调用它会导致我们之前看到的相同错误。
class foo { #brand; static isfoo(obj) { return #brand in obj; }}const x = new foo();// ✅ works, it returns truefoo.isfoo(x);// ✅ works, it returns falsefoo.isfoo({})// ❌ uncaught syntaxerror: private field '#brand' must be declared in an enclosing class#brand in x
了解有关该提案的更多信息。https://github.com/tc39/proposal-private-fields-in-in
最后的想法
这是一个有趣的版本,它提供了许多小而有用的功能,例如 at、private fields和error cause。当然,error cause会给我们的日常错误跟踪任务带来很多清晰度。
一些高级功能,如top-level await,在使用它们之前需要很好地理解。它们可能在你的代码执行中产生不必要的副作用。
【相关推荐:javascript视频教程、编程视频】
以上就是javascript更新到了es几的详细内容。