2015年12月9日 星期三

Trick to use static variables in javascript

Maybe people that have background in C language know how to do this because in C language there is a static keyword to declare a static variable. What is about Javascript?

Well, Javascript doesn't have static keyword. One way to solve this problem, you may use global variable. However, for some people, it will pollute the global namespace. Last night, I read a javascript book, Javascript - The Definitive Guide, 5th edition. The author used closure to achieve this by returning back the anonymous function.


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.



uniqueID(); // 0

uniqueID(); // 1
uniqueID(); // 2

reference : http://chamnapchhorn.blogspot.tw/2008/07/trick-to-use-static-variables-in.html

沒有留言:

wibiya widget