使用class?關(guān)鍵字定義了一個Foo類 。這個類有兩個成員,title和artist?。該artist?成員以井號 (#) 符號為前綴,因此它是私有的。我們允許在構(gòu)造函數(shù)中設(shè)置這些字段,構(gòu)造函數(shù)必須this.#artist再次使用哈希前綴訪問,不然會被覆蓋成公共字段。
 本文盤點ECMAScript 2022 中的新特性,包括頂級等待、RegExp 匹配索引、新的公共和私有類字段等。
一、公共和私有實例字段
最新的 ES13 規(guī)范允許我們將成員字段內(nèi)聯(lián)定義為類主體的一部分,我們可以使用#來表示私有字段。
class Foo {
    title = "";
    #artist = "";
    constructor(title, artist){
      this.title = title;
      this.#artist = artist;
    }
}
let foo = new Song("public", "privite property");
console.log(song1.title);
// “property”
console.log(song1.artist);
// undefined使用class?關(guān)鍵字定義了一個Foo類 。這個類有兩個成員,title和artist?。該artist?成員以井號 (#) 符號為前綴,因此它是私有的。我們允許在構(gòu)造函數(shù)中設(shè)置這些字段,構(gòu)造函數(shù)必須this.#artist再次使用哈希前綴訪問,不然會被覆蓋成公共字段。
二、私有實例方法和訪問器
class PageVM {
  title = "";
  #artist = "";
  constructor(title, artist){
    this.title = title;
    this.#artist = artist;
  }
  get getArtist() {
    return this.#artist;
  }
  set #setArtist(artist) {
    this.#artist = artist;
  }
}三、將靜態(tài)成員添加到類
class Article {
  static label = "ES 2022";
}
console.log(Article.label) // Es 2022
/***** 私有靜態(tài)字段 ********/
class Article {
  static #label = "es 2022";
  constructor() {
    console.log(Article.#label) // es 2022
  }
}
let son = new Article();
Article.#label // undefined可以有一個帶有 static 的靜態(tài)私有字段#label;即私有靜態(tài)字段。
四、/d 正則
提供一個indices數(shù)組,數(shù)值為匹配到的字符串的開始和結(jié)束位置
const str = 'Hello world!';
//查找"Hello"
const patt = /Hello/d;
const res = patt.exec(str);
console.log(res);
/*[
  'Hello',
  index: 0,
  input: 'Hello world!',
  groups: undefined,
  提供數(shù)組indices: [ [ 0, 5 ], groups: undefined ]
]*/
五、 頂層await
const sleep = (delay = 1000) => {
  return new Promise((resolve) => {
    setTimeout(() {
      resolve(true);
    }, delay);
  });
};
await sleep(3000);之前的await只能允許在async函數(shù)中使用,ES13允許在頂層使用await函數(shù)
六、檢查私有字段是否存在
class PageVm { 
  #artist; 
  checkField(){ 
    return #artist in this;
  } 
}
let vm = new PageVm();
vm.checkField(); // true七、at 負索引查找
const list = ['apple', 'banner', 'Grape', 'other', 'pear'];
list[0]; // apple
list.at(0); // apple
list.at(-1); // pear
list.at(-2); // other
八、hasOwn
let foo = Object.create(null);
foo.hasOwnProperty = function(){};
Object.hasOwnProperty(foo, 'hasOwnProperty'); // Error: Cannot convert object to primitive value
Object.hasOwnProperty.call(foo, 'hasOwnProperty') // true
Object.hasOwn(foo, 'hasOwnProperty'); // true
九、錯誤原因
function errormsg() {
  try {
    noFun();
  } catch (err) {
    // 支持原因
    throw new Error('causeError', { cause: 'fun為定義,diy error msg' });
  }
}
function goFun() {
    try {
    errormsg();
  } catch (err) {
    console.log(`Cause by: ${err.cause}`); // Cause by: fun為定義,diy error msg
  }
}
goFun()Error,支持包含錯誤原因支持,這允許在錯誤鏈中進行類似 Java 的堆棧跟蹤。錯誤構(gòu)造函數(shù)現(xiàn)在允許包含一個cause字段的選項。
總結(jié):
ES每次更新都帶了便于開發(fā)者操作的簡化和新特性。
- 數(shù)組的負索引,不需要知道數(shù)組的長度就可以進行一些操作
 - class的私有屬性和方法,提供了更多的操作空間
 - Error對象的錯誤信息,利于排查
 - 頂層await不必再在外層包裹異步函數(shù)