Example 1 — Runs at definition
Before you construct instances.
JavaScript
let n = 0; class A { static { n = 1; } }
console.log(n); How It Works
- Block ran when class evaluated.
A static { } block runs once when the class is evaluated—useful for multi-step static setup that is awkward as field initializers.
class Config {
static values = {};
static {
this.values.mode = "dev";
}
}
console.log(Config.values.mode); Before you construct instances.
let n = 0; class A { static { n = 1; } }
console.log(n); Allowed; run in order.
class A { static a = 0; static { this.a = 1; } static { this.a = 2; } }
console.log(A.a); Blocks can touch #statics.
class A { static #x; static { this.#x = 5; } static getX(){ return this.#x; } }
console.log(A.getX()); CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful