Static variables in JavaScript

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

How can I create static variables in Javascript?

相关标签:
30条回答
  • 2020-11-22 02:32

    There are other similar answers, but none of them quite appealed to me. Here's what I ended up with:

    var nextCounter = (function () {
      var counter = 0;
      return function() {
        var temp = counter;
        counter += 1;
        return temp;
      };
    })();
    
    0 讨论(0)
  • 2020-11-22 02:32

    In JavaScript variables are static by default. Example:

    var x = 0;
    
    function draw() {
        alert(x); //
        x+=1;
    }
    
    setInterval(draw, 1000);
    

    The value of x is incremented by 1 every 1000 milliseconds
    It will print 1,2,3 so forth

    0 讨论(0)
  • 2020-11-22 02:32

    Working with MVC websites that use jQuery, I like to make sure AJAX actions within certain event handlers can only be executed once the previous request has completed. I use a "static" jqXHR object variable to achieve this.

    Given the following button:

    <button type="button" onclick="ajaxAction(this, { url: '/SomeController/SomeAction' })">Action!</button>
    

    I generally use an IIFE like this for my click handler:

    var ajaxAction = (function (jqXHR) {
        return function (sender, args) {
            if (!jqXHR || jqXHR.readyState == 0 || jqXHR.readyState == 4) {
                jqXHR = $.ajax({
                    url: args.url,
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify($(sender).closest('form').serialize()),
                    success: function (data) {
                        // Do something here with the data.
                    }
                });
            }
        };
    })(null);
    
    0 讨论(0)
  • 2020-11-22 02:33

    If you want to declare static variables for creating constants in your application then I found following as most simplistic approach

    ColorConstants = (function()
    {
        var obj = {};
        obj.RED = 'red';
        obj.GREEN = 'green';
        obj.BLUE = 'blue';
        obj.ALL = [obj.RED, obj.GREEN, obj.BLUE];
        return obj;
    })();
    
    //Example usage.
    var redColor = ColorConstants.RED;
    
    0 讨论(0)
  • 2020-11-22 02:33

    The closest thing in JavaScript to a static variable is a global variable - this is simply a variable declared outside the scope of a function or object literal:

    var thisIsGlobal = 1;
    
    function foo() {
        var thisIsNot = 2;
    }
    

    The other thing you could do would be to store global variables inside an object literal like this:

    var foo = { bar : 1 }
    

    And then access the variabels like this: foo.bar.

    0 讨论(0)
  • 2020-11-22 02:33

    You can define static functions in JavaScript using the static keyword:

    class MyClass {
      static myStaticFunction() {
        return 42;
      }
    }
    
    MyClass.myStaticFunction(); // 42
    

    As of this writing, you still can't define static properties (other than functions) within the class. Static properties are still a Stage 3 proposal, which means they aren't part of JavaScript yet. However, there's nothing stopping you from simply assigning to a class like you would to any other object:

    class MyClass {}
    
    MyClass.myStaticProperty = 42;
    
    MyClass.myStaticProperty; // 42
    

    Final note: be careful about using static objects with inheritance - all inherited classes share the same copy of the object.

    0 讨论(0)
提交回复
热议问题