Static variables in JavaScript

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

How can I create static variables in Javascript?

30条回答
  •  不思量自难忘°
    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.

提交回复
热议问题