How to achieve static variable in javascript

2 Ways :

1) Make use of the fact that functions are objects and can have properties
(Even using “this” instead of uniqueID inside the function will do)

function uniqueID() {
    // Check to see if the counter has been initialized
    if ( typeof uniqueID.counter == 'undefined' ) {
        // It has not... perform the initialization
        uniqueID.counter = 0;
    }
    uniqueID.counter++;
    return (uniqueID.counter);
}

console.log(uniqueID());
console.log(uniqueID());


2) Using closure and function expressions

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.

console.log(uniqueID());
console.log(uniqueID());


This entry was posted in Javascript. Bookmark the permalink.