Using Closures to Keep the Global Namespace Clean Saturday, 17 December 2005
I've recently adopted technique to keep the global namepsace clean. The technique is to use an Anonymous Function for a closure.
Problem: A set of globally accessible functions or objects share a common need for a helper function or variable that is not needed anywhere else.
Solution: Create an anonymous function to encapsulate the global and functions or objects and limit the scope of the helper functions and variables by declaring them locally (by using the var or function in the start of the declaration.
Example:
(function() { // global methods. hasToken = function(s, token) { return getTokenizedExp(token,"").test(s); }; removeClass = function(el, klass) { el.className = el.className.replace(getTokenizedExp(klass, "g")," ").normalize(); }; addClassConditionally = function(el, klass) { if(!getTokenizedExp(klass).test(el.className)) el.className += " " + klass; }; // local variables and functions. var TokenizedExps = { }; function getTokenizedExp(token, flag){ return (TokenizedExps[token] || (TokenizedExps[token] = new RegExp("(^|\\s)"+token+"($|\\s)", flag))); } })(); // anonymous function immediately invoked with ().
Advantages: Easy to implement. Little change required. No performance hit.
Variables can be hidden in scope.
Consequences:
The local variables will not be accessible outside of the anonymous function. The long-term effect this can have is that if the need for those variables arises outside of the context of the anonymous function, then either 1) the those local variables will have to be made public, or 2) the code that needs those variables will need to be placed into the enclosing anonymous function.
Use this technique to clean up the global namespace.
By creating and invoking an anonymous function, we can define public objects or methods that use the enclosing function's local variables and functions.
Technorati Tags: JavaScript Closure


AnimTree