[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:
function WikitechyClass () 
{ 
// constructor function
  var privateVariable = "foo";  // Private variable 

  this.publicVariable = "bar";  // Public variable 

  this.privilegedMethod = function () 
  {  
  // Public Method
    alert(privateVariable);
  };
}

// Instance method will be available to all instances but only load once in memory 
WikitechyClass.prototype.publicMethod = function () 
{    
  alert(this.publicVariable);
};

// Static variable shared by all instances
WikitechyClass.staticProperty = "baz";

var myInstance = new WikitechyClass();

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:
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 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:
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.

We will be getting same output except, this time, the incremented value is returned, instead of displayed.

Solution 3:

We can do it through an IIFE (Immediately Invoked Function Expression):

var incre = (function () 
{
    var j = 1;

    return function () 
    {
        return j++;
    }
})();

incre(); // returns 1
incre(); // returns 2

Solution 4:

We can use arguments.callee to store "static" variables (this is useful in anonymous function too):

function () 
{
  arguments.callee.myStaticVar = arguments.callee.myStaticVar || 1;
  arguments.callee.myStaticVar++;
  alert(arguments.callee.myStaticVar);
}

Solution 5:

If we want to declare static variables for creating constants in our application then we found following as most simplistic approach

FruitConstants = (function()
{
    var obj = {};
    obj.APPLE = 'apple';
    obj.ORANGE = 'orange';
    obj.MANGO = 'mango';
    obj.ALL = [obj.APPLE, obj.ORANGE, obj.MANGO];
    return obj;
})();
//Example usage.
var appleFruit = FruitConstants.APPLE;


Related Searches to javascript tutorial - Static variable in javascript