ES6 Class Variable Alternatives
In ES5, classes are commonly created using frameworks with a pattern that includes class variables. However, in ES6, there is no built-in mechanism for creating class variables.
To address this, various approaches have been proposed, but none have proven fully satisfactory. For instance, creating a ClassConfig handler and passing a separate parameter object, or using WeakMaps, have been considered but have limitations.
In 2018, a stage 3 proposal for class variables was introduced. This proposal allows the use of the following syntax within class declarations/expressions:
varName = value
This syntax defines a variable within the class. However, the proposal is still under development and has not yet been finalized.
According to the ES wiki, the decision against including class variables in the ES6 specification was intentional. Class definitions were intended to declare the capabilities of a class, rather than its members. Properties specified in class definitions are assigned attributes as if they appeared in an object literal.
Therefore, to define class variables, the preferred approach is to use the constructor:
constructor(){ this.foo = bar }
An alternative proposal for ES7 is in development, which aims to enable more concise instance variables through class declarations and expressions. This proposal is still under discussion and has not yet been finalized.
The above is the detailed content of How are Class Variables Implemented in ES6 and Beyond?. For more information, please follow other related articles on the PHP Chinese website!