Author: Dr. Axel Rauschmayer
Have a dream, have dry goods, wechat search [big Move the world] pay attention to this in the early morning is still in the bowl washing wisdom. In this paper, making github.com/qq449245884… Has been included, a line of large factory interview complete test sites, information and my series of articles.
Ron Buckton’s ECMAScript proposal “Class Static Initializer Blocks” is in its fourth phase, planned for ECMAScript 2022.
To create an instance of a class, there are two structures in JavaScript:
- Field: Create (optionally initialized) instance properties.
- Constructor: a block of code that executes before setup completes.
For the static part of the class, we only have static fields. ECMAScript proposes to introduce static initializer blocks for classes, which roughly behave for static classes as constructors do for instances.
1. Why do we need static blocks in classes?
When setting static fields, using external functions usually works just fine:
class Translator {
static translations = {
yes: 'ja',
no: 'nein',
maybe: 'vielleicht',
};
static englishWords = extractEnglish(this.translations);
static germanWords = extractGerman(this.translations);
}
function extractEnglish(translations) {
return Object.keys(translations);
}
function extractGerman(translations) {
return Object.values(translations);
}
Copy the code
Using the external functions extractEnglish() and extractGerman() works well in this case because we can see that they are called from within the class and they are completely independent of the class.
If we want to set two static fields at the same time, things become less elegant.
class Translator { static translations = { yes: 'ja', no: 'nein', maybe: 'vielleicht', }; static englishWords = []; static germanWords = []; static _ = initializeTranslator( // (A) this.translations, this.englishWords, this.germanWords); } function initializeTranslator(translations, englishWords, germanWords) { for (const [english, german] of Object.entries(translations)) { englishWords.push(english); germanWords.push(german); }}Copy the code
This time, there are several problems.
-
Calling initializeTranslator() is an additional step that is either performed outside of the class after it has been created. Or do it through A workaround (line A).
-
InitializeTranslator () cannot access the Translator’s private data.
We have A more elegant solution with the proposed static block (line A).
class Translator { static translations = { yes: 'ja', no: 'nein', maybe: 'vielleicht', }; static englishWords = []; static germanWords = []; static { // (A) for (const [english, german] of Object.entries(this.translations)) { this.englishWords.push(english); this.germanWords.push(german); }}}Copy the code
2. A more complicated example
One way to implement enumerations in JavaScript is through the superclass Enum with accessibility
class Enum {
static collectStaticFields() {
// Static methods are not enumerable and thus ignored
this.enumKeys = Object.keys(this);
}
}
class ColorEnum extends Enum {
static red = Symbol('red');
static green = Symbol('green');
static blue = Symbol('blue');
static _ = this.collectStaticFields(); // (A)
static logColors() {
for (const enumKey of this.enumKeys) { // (B)
console.log(enumKey);
}
}
}
ColorEnum.logColors();
// Output:
// 'red'
// 'green'
// 'blue'
Copy the code
We need to collect static fields so that we can iterate over the key of the enumeration item (line B). This is the last step after you have created all the static fields. Again, we use A workaround (line A) where static blocks are more elegant.
Details of 3.
The exact contents of a static block are relatively logical (by contrast, the rules for instance members are more complex) :
- Each class can have more than one static block.
- The execution of the static block is interleaved with the execution of the static field initializer.
- Static members of a superclass are executed before static members of a subclass.
The following code shows these rules:
class SuperClass {
static superField1 = console.log('superField1');
static {
assert.equal(this, SuperClass);
console.log('static block 1 SuperClass');
}
static superField2 = console.log('superField2');
static {
console.log('static block 2 SuperClass');
}
}
class SubClass extends SuperClass {
static subField1 = console.log('subField1');
static {
assert.equal(this, SubClass);
console.log('static block 1 SubClass');
}
static subField2 = console.log('subField2');
static {
console.log('static block 2 SubClass');
}
}
// Output:
// 'superField1'
// 'static block 1 SuperClass'
// 'superField2'
// 'static block 2 SuperClass'
// 'subField1'
// 'static block 1 SubClass'
// 'subField2'
// 'static block 2 SubClass'
Copy the code
4. Support static block like in the engine
- V8: unflagged in v9.4.146 (source)
- SpiderMonkey: behind a flag in v92, intent to ship unflagged in v93 (source)
- TypeScript: v4.4 (source)
5. Is JS becoming too Java and/or messy?
This is a small feature that won’t compete with other features. Static _ =… To run static code. Static blocks mean that this workaround is no longer needed.
Beyond that, classes are just one of many tools on the JavaScript programmer’s belt. Some of us use it, others don’t, and there are many alternatives. Even JS code that uses classes often uses functions and tends to be lightweight.
6. Summary
Class static block is a relatively simple feature that complements the static functionality of a class. Roughly speaking, it is a static version of the instance constructor. It is mainly useful when we need to set more than one static field.
~ over, I am brush bowl wisdom, inspirational and so on after retirement, to go home to set the stall, we see next period!
The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, I recommend a good BUG monitoring tool for youFundebug.
Original text: 2 ality.com/2021/09/cla…
communication
Have a dream, have dry goods, wechat search [big Move the world] pay attention to this in the early morning is still in the bowl washing wisdom.
In this paper, making github.com/qq449245884… Has been included, a line of large factory interview complete test sites, information and my series of articles.