Privatize a Group of JavaScript Functions
It’s a common problem in JavaScript: to use private functions you define them as an object. Later, when interfacing this object with some JavaScript library, you discover that several of the namespaces overlap.
While there is certainly some debate as to how to write an unobtrusive set of JavaScript functions, the most elegant solution is as always very simple. Basically, you wrap the set of functions in a nameless function, and then call this function immediately. The syntax we are going to use works like this:
(function(argument) {
alert(argument);
}) ('What you want to alert');
If you’re unfamiliar with the notation, we are declaring a nameless function, then calling this function immediately with the final set of parentheses.
This is an excellent way to isolate any functions since everything is protected within the scope of the function. Now let’s strip it down a bit, and privatize our function library:
(function() {
/** some functions here **/
}) ();
Now you’re probably thinking, “That’s great, we wanted our functions to be isolated—just not from ourselves.” Well don’t worry, we can easily export some of the functions to be publicly available:
(function() {
function public_function() {
}
function private_function() {
}
window['newNamespace'] = {};
window['newNamespace']['public_function'] = public_function();
}) ();
The first thing we do is define an object ‘newNamespace’ on the window level. Next we export the public_function() to that namespace. Now we can call this function from anywhere outside of this library, using: newNamespace.public_function().
This is an excellent technique to protect some functions and export others, and makes object oriented JavaScript operate a little closer to more robust programming languages.
Tags: JavaScript, library, namespace, object oriented, scope, unobtrusive