class-static-block proposal 2021.9.1 is a proposal based on Class enhancement.
This week we will discuss this feature in conjunction with the article ES2022 feature: class static initialization blocks
Overview
Why do we need the grammar of class static block? One of the reasons is the flexible assignment requirements for Class static variables. Take the following as an example. If we want to initialize static variables in batches inside the Class, we have to write a useless _
variable for initialization logic:
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);
}
}
And why do we initializeTranslator
outside? Just because you can't write code blocks inside a Class, this causes a serious problem. External functions cannot access the internal properties of the Class, so you need to do a lot of boring value passing.
From this example, we can see that in order to customize a piece of static variable initialization logic, we need to make two compromises:
- Define a function externally and accept a large number of Class member variables to pass parameters.
- Define a meaningless variable
_
inside Class to start this function logic.
There is really no code to pursue. Wouldn't it be concise if we do this logic inside the Class? This is the class static block feature:
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);
}
}
}
As you can see, the static
keyword is not followed by variables, but directly followed by a code block, which is the characteristic of the class static block syntax. Inside this code block, all member variables of Class this
, including private variables of #
The original introduction to the use of this feature is over, and one detail is mentioned at the end, which is the order of execution. That is, all static
variables or blocks are executed in order, and the parent class is executed first:
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'
Therefore, multiple class static blocks are allowed in the Class, as well as parent classes and subclasses. The results of different execution orders must be different. This option is left to the user, because the execution order is the same as the writing order.
intensive reading
Combined with the proposal, the class static block has another motivation, which is to give a mechanism to access private variables:
let getX;
export class C {
#x
constructor(x) {
this.#x = { data: x };
}
static {
// getX has privileged access to #x
getX = (obj) => obj.#x;
}
}
export function readXData(obj) {
return getX(obj).data;
}
Theoretically, the class private variables cannot be accessed from the outside anyway, but the readXData
above example is fine, and there will be no runtime error. The reason is that the entire process is legal. The most important reason is that the class static block can access the private at the same time. Variables and global variables, so you can use them to do a "combining inside and outside".
But I don’t think this is a good idea, but rather like a "BUG", because any breakthrough to the regulations will bury hidden dangers for maintainability, unless this feature is used in a stable tool and framework layer for some convenience. Sex work ultimately improves the experience of applying coding, and this usage is acceptable.
Finally, we must realize that class static block does not add new features in essence. We can use ordinary static variables instead, but it is very unnatural to write, so this feature can be understood as a complement to defects or as a syntactic improvement.
Summarize
In general, the class static block creates a block scope in the Class. This scope has the privilege to access the private variables inside the Class, and this block scope is only initialized and executed once when the engine is called, which is more convenient. Grammar.
There are some objections at the bottom of the original text, saying that this is a complication of JS, and there are also voices such as JS becoming more and more like Java, but I agree more with the author’s point that Class in Js is not all, and now more and more code Using functional grammar, there will be a large number of function declarations even in the scene where Class is used, so the proposal of class static block does not actually give developers much perception.
The discussion address is: Intensive Reading "class static block" · Issue #351 · dt-fe/weekly
If you want to participate in the discussion, please click here , there is a new theme every week, weekend or Monday. Front-end intensive reading-to help you filter reliable content.
Follow front-end intensive reading WeChat public
<img width=200 src="https://img.alicdn.com/tfs/TB165W0MCzqK1RjSZFLXXcn2XXa-258-258.jpg">
Copyright statement: Freely reproduced-non-commercial-non-derivative-keep the signature ( Creative Commons 3.0 License )
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。