Static variables in JavaScript

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

How can I create static variables in Javascript?

30条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 02:36

    I use static function variables a lot and it's a real shame JS doesn't have a built-in mechanism for that. Too often I see code where variables and functions are defined in an outer scope even though they're just used inside one function. This is ugly, error prone and just asking for trouble...

    I came up with the following method:

    if (typeof Function.prototype.statics === 'undefined') {
      Function.prototype.statics = function(init) {
        if (!this._statics) this._statics = init ? init() : {};
        return this._statics;
      }
    }
    

    This adds a 'statics' method to all functions (yes, just relax about it), when called it will add an empty object (_statics) to the function object and return it. If an init function is supplied _statics will be set to init() result.

    You can then do:

    function f() {
      const _s = f.statics(() => ({ v1=3, v2=somefunc() });
    
      if (_s.v1==3) { ++_s.v1; _s.v2(_s.v1); }
    } 
    

    Comparing this to an IIFE which is the other correct answer, this has the disadvantage of adding one assignment and one if on every function call and adding a '_statics' member to the function, however there are a few advantages: the arguments are there at the top not in the internal function, using a 'static' in the internal function code is explicit with an '_s.' prefix, and it is overall simpler to look at and understand.

提交回复
热议问题