Vincenzo Alcamo wrote to me with another practical use for closures in JavaScript. Vincenzo is working on a JavaScript library he calls XMLLib, based on the Sarissa library. To prevent his library from cluttering the global namespace, Vinceno defines his symbols in his own XMLLib namespace, of course.
But he goes one step further. In Vincenzo's code, only publically exported methods and properties ever get stored in the XMLLib object. Internal, helper methods that are not intended for public use exist in a closure, where all the public methods can use them but where they are hidden from everyone else.
Schematically, the code looks like this:
// Create an empty namespace
XMLLIB = {}
(function() { // anonymous function creates a closure for us
// Thi s is a private method that stays hidden within the closure
function private_utilty_method() { /* utility code here */ }
// This method is exported into the XMLLib namespace, so it is a public method
// But since it is defined here, it can call private methods like the one above.
XMLLib.publicMethod = function() { /* ... */}
})(); // Close function definition and invoke it all at once
Contrast this approach to private symbols with that taken by JSAN. In that framework, a namespace may contain a mix of public and private symbols. The namespace also declares an array of symbols that should be exported by default, and an array of symbol that are allowed to be exported from the namespace. Any symbols excluded from these arrays are private, and the JSAN exporter functions will not copy them into the global namespace. That is, the JSAN framework does not have true privacy via closures, but defines a convention which, when followed, provides a measure of privacy.
Thanks for the tip, Vincenzo!



