How can I create static variables in Javascript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
There are 4 ways to emulate function-local static variables in Javascript.
Method 1: Using function object properties (supported in old browsers)
Method 2: Using a closure, variant 1 (supported in old browsers)
Method 3: Using a closure, variant 2 (also supported in old browsers)
Method 4: Using a closure, variant 3 (requires support for EcmaScript 2015)
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:
The other thing you could do would be to store global variables inside an object literal like this:
And then access the variabels like this:
foo.bar
.Window level vars are sorta like statics in the sense that you can use direct reference and these are available to all parts of your app
You do it through an IIFE (immediately invoked function expression):
If you want to declare static variables for creating constants in your application then I found following as most simplistic approach
You can create a static variable in JavaScript like this below. Here
count
is the static variable.You can assign values to the static variable using either the
Person
function, or any of the instances: