Static initialization blocks in JavaScript classes
- Published at
- Updated at
- Reading time
- 2min
I've been reading Jake's guide on custom elements and when/where to define a new custom element. It's a good and quick read, so go check it out!
His final custom element snippet includes something I haven't seen before.
class MyElement extends HTMLElement {
// Static class property
static tag = "my-element";
// Static class method
static define(tag = this.tag) {
// ...
}
// ๐ What's this is?
static {
// ...
}
}
The class defines two static class members. One is a class property (tag
), and the other is a class method (define
). Both static class members can be called without initializing the class and creating an instance.
class MyElement extends HTMLElement {
static tag = "my-element";
static define(tag = this.tag) {
console.log('define was called...')
}
}
// access the `tag` property without initializing a new class instance
console.log(MyElement.tag); // 'my-element'
// call the `define` method without initializing a new class instance
MyElement.define(); // 'define was called...'
Cool, that's what static
is for. But what's up with this nameless static
block?
Apparently, JavaScript classes support static initialization blocks. These initialization blocks are called during class initialization (don't confuse them with when you initialize a new object of a class).
So, whenever the JavaScript parser rolls over and parses the class MyElement
, it'll call its static
block. That's neat!
class MyElement extends HTMLElement {
static {
console.log('class was initialized...')
}
}
// automatically logs "class was initialized..."
Static initialization blocks can be extremely handy for conditionally registering custom elements (as Jake showed) or dynacially (uhm... dynamically?! ๐ ) setting up a shared property across class instances. I could think of a shared database connection or something like this.
But can we all use static initialization blocks today?
94 | 94 | 94 | 93 | 93 | 16.4 | 16.4 | 17.0 | 94 |
Apparently, static initialization blocks have been part of ECMAScript 2022, and they're supported across all browsers. Well, today I learned!
Join 5.5k readers and learn something new every week with Web Weekly.