/ 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.
Expand |
Embed | Plain Text
var uid = ( function(){ var id=0; return function(){ return id++ ; }; } )(); //then just say: alert(uid()); //alert 1 alert(uid()); //alert 2 alert(uid()); //etc.
Comments
Subscribe to comments
You need to login to post a comment.

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++;}})();