the Great JavaScript Closure Pattern explained
Most of you will have seen it in jQuery, but also maybe in Mustache.js, or even another library:
You know you need this somehow to protect the global namespace etc., But how does it work again? Follow along.
It’s just a function call
Yep, that’s right. You know that in JavaScript you can define anonymous functions:
Well, you can also call them immediately and that's what the above code does. With that out of the way, let's concentrate on the function body and remember later to see why we would want the function to be executed.
Why you need a function
What does a JavaScript program need like humans need oxygen to breathe? Scope. JavaScript burns scopes faster than a pack of cigarettes in a noir movie, because loops, if/else branches have no scope of their own. The only thing that has a scope is a function and that's why you create functions all the time.
When you think of it, it's pretty cool. It's like every function was its own little package or module, for languages which have that sort of thing. So just go at it, define whatever variable or and function you want in the closure body.
Moving it outside
Done? But how can I use all of this stuff in my web page?, you will ask. Well, you need to move it outside in a convenient wrapper. The trick is that you only really need to move the interface, the functions that need to be used first hand in the outside world. All the rest can remain forever inside the closure and still be accessible from what you exported.
There are two main techniques being used, but both involve first creating an object to hold your interface.
Building an object for outside
Just do
Inside the braces you can, as already said, access anything that's defined inside the closure. There are a couple of other techniques for building your object, but let's not cover them here. Let's move on to the essential.
Bringing it outside
Finally! As already said, there are two ways to do it. First way: just before the end of your big encircling closure/anonymous function, do
and your object will be accessible anywhere with all its methods intacts. In this case, you need to execute the anonymous function to perform this assignment.
The other solution is to assign the result of the execution of the anonymous function to a variable outside the closure.
Happy ending
So now our object is out there, making its methods available to the whole world; the global namespace is intact; and you have one thing less to be confused about.
As you explore other JavaScript libraries, you will meet other variations on this pattern. Experimentation is still in full swing in the JavaScript community, but that’s why it’s fun and one day, you too might make the next big invention (but spiky hair is not en vogue anymore).