Neat little example of a useful Javascript closure
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());
December 15th, 2007 at 1:46 pm
[…] When I want to implement a requirement, such as a business rule or DHTML behavior in JavaScript, sometimes I find that I don’t know how to implement that behavior. Sometimes this might be because the requirement is complex, as in the case of DHTML animation. Or the algorithm I am searching for may just be obscure, such as a unique ID generator that uses a closure instead of a global counter. […]