🔰init static property
🚧 under construction ->
Last updated
Was this helpful?
🚧 under construction ->
Last updated
Was this helpful?
Was this helpful?
JS ⟩ value ⟩ object ⟩ class ⟩ member ⟩ static ⟩ init
static block:用於對 static property 的初始化
web component:可用這裡的方法初始化 component 的靜態屬性
1
👍
✅ 延遲初始化
⚠️ 額外的私有靜態屬性
2
⚠️ 不夠模組化
3
👍
✅ 模組化
⚠️ ES2022
4
class ClassB {
// ClassB.CONSTANT
// 方法二:在 class 定義後立即計算賦值
// • 缺點:
// ❗程式碼不夠模組化
static CONSTANT; // 1. 先宣告
}
// block
{
// 複雜的初始化邏輯 ...
ClassB.CONSTANT = 200; // 2. 後面立即計算賦值
}
class ClassC {
// ClassC.CONSTANT
// 方法三:使用 static block (ES2022)(方法二的現代版)
// • 優點:
// ✅ 模組化(沒有程式碼外漏於 class 定義外)
// ✅ 語法簡潔,不需外部的計算(方法二)、或內部的靜態方法(方法四)
static CONSTANT; // 1. 先宣告
// ⭐️ static block (ES2022)
// ⭐️ in static method/block/getter, this == class itself.
static {
// 複雜的初始化邏輯 ...
this.CONSTANT = 300; // 2. 後面立即計算賦值
}
}
class ClassD {
// ClassD.CONSTANT
// 方法四:使用 static method 賦值
// • ✅ 優點:模組化(沒有程式碼外漏於 class 定義外)
// ⭐️ in static method/block/getter/declaration, this == class itself.
static CONSTANT = this.initStaticConstant();
static initStaticConstant() {
// 複雜的初始化邏輯 ...
return 400;
}
}
class A {
// ⭐️ "#" means "private"
static #e; // A.#e (private static property: uninitialized)
static get #f() { ... } // A.#f (private static getter)
static #g() { ... } // A.#g() (private static method)
}
class ClassA {
// ClassA.CONSTANT
// 方法一:使用 static getter(傳回 ClassA._CONSTANT 的值)
// • 優點:
// ✅ 延遲初始化
// • 缺點:
// ❗ 額外的私有靜態屬性 (ClassA._CONSTANT)
// ⭐️ 注意:不能省略 `get`,不然會變成 static method❗
static get CONSTANT() {
// 如果還沒初始化
// ⭐️ in static method/block/getter, this == class itself.
if (!this._CONSTANT) {
// 執行初始化 ...,然後將結果存在私有靜態屬性中
this._CONSTANT = 100;
}
return this._CONSTANT;
}
}
✅ 模組化