这篇文章盘点了ECMAScript2022的新特性,包括顶层等待、RegExp匹配索引、新的公共和私有类字段等等。1.公有和私有实例字段最新的ES13规范允许我们将成员字段内联定义为类体的一部分,我们可以使用#来表示私有字段。Foo类{title="";#艺术家=“”;构造函数(标题,艺术家){this.title=title;这个。#artist=艺术家;}}letfoo=newSong("public","privateproperty");console.log(song1.title);//"property"console.log(song1.artist);//undefined使用类关键字。这个类有两个成员,title和artist。艺术家成员以哈希(#)符号为前缀,因此它是私有的。我们允许在构造函数中设置这些字段,并且必须使用this.#artist再次使用哈希前缀访问构造函数,否则它将被覆盖为公共字段。2.私有实例方法和访问器类PageVM{title="";#艺术家=“”;构造函数(标题,艺术家){this.title=title;这个。#artist=艺术家;}getgetArtist(){返回这个.#artist;}set#setArtist(artist){this.#artist=artist;}}3.给类添加静态成员classArticle{staticlabel="ES2022";}console.log(Article.label)//Es2022/*****privatestaticfield********/classArticle{static#label="es2022";constructor(){console.log(Article.#label)//es2022}}letson=newArticle();Article.#label//undefined可以有一个静态私有字段#labelwithstatic;即,私有静态字段。4./d定时提供一个索引数组,值为匹配字符串的起止位置conststr='Helloworld!';//查找“Hello”constpatt=/Hello/d;constres=patt。exec(str);console.log(res);/*['Hello',index:0,input:'Helloworld!',groups:undefined,提供数组索引:[[0,5],groups:undefined]]*/五、顶层awaitconstsleep=(delay=1000)=>{returnnewPromise((resolve)=>{setTimeout((){resolve(true);},delay);});};await睡眠(3000);之前的await只能在async函数中使用,ES13允许在顶层使用await函数六、检查是否有私有字段classPageVm{#artist;checkField(){在此返回#artist;}}letvm=newPageVm();vm.checkField();//true七,在负数索引处搜索constlist=['apple','banner','Grape','other','pear'];list[0];//applelist.at(0);//applelist.at(-1);//pearlist.at(-2);//其他八个,hasOwnletfoo=Object.create(null);foo.hasOwnProperty=function(){};Object.hasOwnProperty(foo,'hasOwnProperty');//错误:无法将对象转换为原始值Object.hasOwnProperty.call(foo,'hasOwnProperty')//trueObject.hasOwn(foo,'hasOwnProperty');//true九,错误原因functionerrormsg(){try{noFun();}catch(err){//支持reasonthrownewError('causeError',{cause:'funisdefined,diyerrormsg'});}}functiongoFun(){try{errormsg();}catch(err){console.log(`Causeby:${err.cause}`);//Causeby:funisdefined,diyerrormsg}}goFun()Error,支持包括错误原因支持,允许错误链中类似Java的堆栈跟踪错误构造函数现在允许选项包含原因字段。总结:ES的每一次更新都带来了简化和新特性,方便开发者操作。数组的负索引可以在不知道数组长度的情况下对类的私有属性和方法进行一些操作,提供更多的操作空间Error对象的错误信息,有助于排查顶层awaitwithoutwrapping外层异步函数
