In my recent post on creating a jQueryUI widget, I referenced the concept of self-executing anonymous functions. I've actually had a few questions come up at the office lately about how they work, so I figured turning it into a blog post might not be a bad idea. It's an important concept in Javascript many don't know about. Others know how to use them, but don't really understand how or why they work. Today I'll cover step-by-step how to go from a traditional function to a self-executing anonymous function; hopefully it will be clear at the end how these things work.
To see how we get to a self-executing anonymous function, we can take some simple steps. Let's use the following simple block of Javascript for our example.
var test = "a";
function testFunc(foo) {
alert(foo);
}
testFunc(test);
Since functions in Javascript are objects like any other, we can use operators on the object such as the ( and ) grouping operators.
var test = "a";
function testFunc(foo) {
alert(foo);
}
(testFunc)(test);
Groovy. But since we are running the function as soon as we create it, couldn't we combine it into one statement and the function run itself? Obviously we can or this article would have been a short-and-sweet "you can't do it" so...
var test = "a";
(function testFunc(foo) {
alert(foo);
})(test);
Just because the function hasn't been assigned to the name testFunc yet doesn't mean that it's not already an object. And being an object, of the type function, means we can run it. Now, it's a simple step of saying "I don't need to reference this function again--I want it to run and then forget about the function itself. Great, functions in javascript can be anonymous so there's no need to assign it a name:
var test = "a";
(function(foo) {
alert(foo);
})(test);
I'd give a Steve Jobs' style BOOM! but I'm just not sure it's quite that big. What I do know is that these little beauties are great for encapsulating functionality and keeping things out of the global namespace. Take a look at the source code of jQuery and you'll see that the whole library is wrapped in a single, self-executing function that is assigned to the jQuery global object. It's precisely the reason that jQuery doesn't pollute the global namespace nearly as much as other libraries.