Static variables in JavaScript

后端 未结 30 2275
别那么骄傲
别那么骄傲 2020-11-22 01:55

How can I create static variables in Javascript?

30条回答
  •  梦毁少年i
    2020-11-22 02:28

    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.

提交回复
热议问题