A modern way to create a static or class variable for a Javascript class

I hunted for a clear answer to this, and most of what pops up still refers to the old (or I should say "traditional") way of defining classes using function .

According to this SO answer ,

Class properties are not supported in ES2015.

As far as I can tell, the only way to add a static variable to the class is:

https://jsfiddle.net/abalter/fknwx3n4/

 class C { constructor(x) { console.log("in constructor " + x); this.x = x; this.add(this.x); } add(x) { console.log("in add " + x); C.alist.push(x); } show() { console.log("in show"); console.log(C.alist); } } // MUST be done outside of actual class definition. C.alist = []; c1 = new C(5); c1.show(); c2 = new C(10); c1.show(); c2.show(); 

Is this the end of the story? It just seems like it's so weird that you can't do it INSIDE a class definition.

+5
source share
2 answers

You can call a static function that initializes all static members immediately after the class definition, and then further removes this function. (Perhaps there will be a function to reset static variables?)

This will allow you to save all your static variables inside the class declaration.

 class C { static init() { C.alist = []; } constructor(x) {…} add(x) {…} show() {…} } C.init(); delete C.init; 

Another option is to initialize static variables in the constructor, but this requires that at least one object be created before using static variables.

 class C { constructor(x) { C.alist = C.alist || []; … } add(x) {…} show() {…} } 
+1
source

If all you care about is stylistic encapsulation of a class and its static properties in one structure, you should consider using a module template (just like we used it in ES5 to enclose a constructor and prototype).

In ES6, there is also Object.assign , which you could use to do this:

 const C = Object.assign(class { constructor() { … } methods() { … } … }, { of(x) { … }, static_methods() {…}, … static_property: … }); 
0
source

All Articles