[Solved-5 Solutions] Static Variable in JavaScript - JavaScript tutorial
Problem:
How to create Static Variables in Javascript ?
Solution 1:
- If we come from a class-based, strongly typed object-oriented language (like Java, C++ or C#) WE assume that we are trying to create a variable or method associated to a "type" but not to an instance.
- An example using a "classical" approach, with constructor functions maybe could help we to catch the concepts of basic Object Oriented JavaScript:
staticProperty is defined in the WikitechyClass object (which is a function) and has nothing to do with its created instances, JavaScript treats functions as first-class objects , so being an object, we can assign properties to a function.
Solution 2:
- One of the main advandage of JavaScript functions are also objects, which means they can have properties.
- For example the sample code is given below:
- If we call that function several time, you'll see the counter is being incremented.
- Maybe the better solution using the global namespace with a global variable.
- Here we can use simple code for static variables in javascript:
We will be getting same output except, this time, the incremented value is returned, instead of displayed.
Read Also
Scope variable using AngularJSSolution 3:
We can do it through an IIFE (Immediately Invoked Function Expression):
Solution 4:
We can use arguments.callee to store "static" variables (this is useful in anonymous function too):
Solution 5:
If we want to declare static variables for creating constants in our application then we found following as most simplistic approach