I just picked up the 5th edition of David Flanagan’s JavaScript, the Definitive Guide. I find it amusing that that book is the only JavaScript book officially recommended at comp.lang.javascript.
Closures are a powerful feature of JavaScript. However it’s often hard to explain in a few words, just what is useful about closures. Well, here on page 131 of the Rhino book, is the recipe for a unique ID generator that doesn’t require a global counter.
One thing that I personally enjoy about the Flanagan book is that he says things like “don’t pollute the global namespace.” This technique does not pollute the global namespace.
var uid = (
function(){
var id=0;
return function(){
return id++ ;
};
}
)();
//then just say:
alert(uid());
var uid = (function(){var id=0; return function(){return id++ ;};})();