Modern way to create static or Class variable for Javascript class

被刻印的时光 ゝ 提交于 2019-12-07 00:26:40

问题


I've been hunting around for a clear answer to this, and most of what pops up still relates to the old (or should I 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 a class is like:

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? Just seems so strange to not be able to do it INSIDE the class definition.


回答1:


You could call a static function that initializes all the static members immediately after the class is defined, and then optionally delete that function. (Possibly resetting static variables would be a feature?)

This would allow you to keep all of 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 instantiated before the static variables can be used.

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



回答2:


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

In ES6, there is also Object.assign that you could use for this:

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


来源:https://stackoverflow.com/questions/37982610/modern-way-to-create-static-or-class-variable-for-javascript-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!