How can I create static variables in Javascript?
In addition to the rest, there's currently a draft (stage-2 proposal) on ECMA Proposals that introduces static
public fields in classes. (private fields were considered)
Using the example from the proposal, the proposed static
syntax will look like this:
class CustomDate {
// ...
static epoch = new CustomDate(0);
}
and be equivalent to the following which others have highlighted:
class CustomDate {
// ...
}
CustomDate.epoch = new CustomDate(0);
You can then access it via CustomDate.epoch
.
You can keep track of the new proposal in proposal-static-class-features.
Currently, babel supports this feature with the transform class properties plugin which you can use. Additionally, though still in progress, V8 is implementing it.