ES2022 的新功能介紹
5 min readJun 18, 2023
前言
ES2022 已經在 2022 年 6 月更新,這篇文章介紹 chrome 裡面有加入的新功能(持續更新中)。
為什麼只先參考 chrome 加入的功能?
主要是在網路上查到整理的文件很多,有些分享的功能在其他沒有,或是很早就被 nodejs 實作(例如 Top-Level await,在 nodejs 很早就有,但是有網路文件卻列在 ES2022),所以就先選擇一個比較可信的資料來源,當然後面也會附上其他參考的網站。
public / private class field
這個版本中,js class 加入了 public / private 的使用方式來區分變數(原先可能得用 Object.defineProperty 來處理),對工程師來說可是一大福音。
Private class fields
private 的變數和函數,需要有個 public get 或是 set 才可以存取,通常是用來保護變數被任意存取,這裡用 Person 物件作為範例:
class Person {
// all private
#height = 0;
#weight = 0;
#name = '';
constructor (height, weight, name) {
this.#height = height;
this.#weight = weight;
this.#name = name;
}
get height() {
return this.#height;
}
get weight() {
return this.#weight;
}
get name() {
return this.#name;
}
#setWeight (weight) {
this.#weight = weight;
}
gainWeight(weight) {
if (weight < 0) {
return;
}
let w = this.#weight;
w += weight;
this.#setWeight(w);
}
lossWeight(weight) {
if (weight < 0 || weight > this.#weight) {
return;
}
let w = this.#weight;
w -= weight;
this.#setWeight(w);
}
}
const p = new Person(180, 50, 'Adam');
// SyntaxError: Private field '#height' must be declared in an enclosing class
// p.#height = 100;
console.log(p.weight) // 50
// SyntaxError: Private field '#setWeight' must be declared in an enclosing class
// p.#setWeight(10)
p.gainWeight(10)
console.log(p.weight) // 60
範例中定義了 height, weight, name 三個 private 變數,同時我們有定義一些函數和 get 來存取這些變數。
如果直接存取 private 變數或是函數會發生錯誤。
Static class fields
static 的變數或是函數,是不需要實體化物件也可以使用,這裡用 TokenMath 物件作為範例:
class TokenMath {
static MULTIPLIER = 1e10;
static #PRECISION = 1e6;
static #converNumber(i) {
return i * TokenMath.MULTIPLIER / TokenMath.#PRECISION
}
static conver(i) {
return TokenMath.#converNumber(i)
}
}
// TokenMath.MULTIPLIER
// SyntaxError: Private field '#PRECISION' must be declared in an enclosing class
// TokenMath.#PRECISION
// SyntaxError: Private field '#converNumber' must be declared in an enclosing class
// TokenMath.#converNumber(1)
TokenMath.conver(1)
如果直接存取 private 變數或是函數會發生錯誤。
參考資料
https://www.ecma-international.org/publications-and-standards/standards/ecma-262/