Posted By

noah on 05/01/07


Tagged

closure unobtrusive counter flanagan oreilly rhino


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

handcoding


Unique ID generator without a global temp variable


 / Published in: JavaScript
 

This is cool and simple example of a closure. It is from the Flanagan (Rhino) Javascript book, page 131 of the 5th edition.

  1. var uid = (
  2. function(){
  3. var id=0;
  4. return function(){
  5. return id++ ;
  6. };
  7. }
  8. )();
  9. //then just say:
  10. alert(uid()); //alert 1
  11. alert(uid()); //alert 2
  12. alert(uid()); //etc.

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: SkewsMe on February 15, 2010

The first alert(uid()); will alert 0, then 1, 2, etc.

I use a modified version allowing me to reset the id back to zero.

var uid = (function(){var id=0;return function(){if(arguments[0]===0)id=0;return id++;}})();

You need to login to post a comment.