Static variables in JavaScript

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

How can I create static variables in Javascript?

30条回答
  •  离开以前
    2020-11-22 02:28

    You might take advantage of the fact that JS functions are also objects -- which means they can have properties.

    For instance, quoting the example given on the (now vanished) article Static variables in Javascript:

    function countMyself() {
        // Check to see if the counter has been initialized
        if ( typeof countMyself.counter == 'undefined' ) {
            // It has not... perform the initialization
            countMyself.counter = 0;
        }
    
        // Do something stupid to indicate the value
        alert(++countMyself.counter);
    }
    

    If you call that function several time, you'll see the counter is being incremented.

    And this is probably a much better solution than poluting the global namespace with a global variable.


    And here is another possible solution, based on a closure : Trick to use static variables in javascript :

    var uniqueID = (function() {
       var id = 0; // This is the private persistent value
       // The outer function returns a nested function that has access
       // to the persistent value.  It is this nested function we're storing
       // in the variable uniqueID above.
       return function() { return id++; };  // Return and increment
    })(); // Invoke the outer function after defining it.
    

    Which gets you the same kind of result -- except, this time, the incremented value is returned, instead of displayed.

提交回复
热议问题