JavaScript: more about the module pattern

In the previous post, we’ve started looking at the module pattern and how we can use it to write modular JavaScript code. I’ve ended the post mentioning that we still need to discuss an important topic before wrapping up the basics aspects associated with the pattern. If you’ve been following along, you know I’m talking about dependencies. In order to illustrate the topic, I’ll modify the previous example so that we use jQuery to print the message inside an element whose ID will be passed as a parameter. The next snippet shows our final code:

Now, if you’ve been doing JS for some time, you’ve probably noticed something which might get you worried: we’re depending on a global. Technically, $ is an alias to the jQuery global object. In other words, were depending on an implied global and whenever the JS interpreter engine finds one, it’ll have to walk the scope chain backwards until it finds a valid reference (in our example, it’ll walk until it gets to the global scope). Now, in our case, we’d end with an error if jQuery hasn’t been imported before our script gets run. Things could be worse though. For instance, suppose we were using the implied global in the left sign of an assignment expression. In that case, if the global didn’t exist, we’d end up creating a new one (if we were not running in strict mode).

Fortunately, there’s an easy solution for this kind of problem: I’m talking about global imports. Whenever you need a reference to a global variable within the closure created by the anonymous function, you just pass it as a parameter. The next snippet shows this strategy in action:

Even though we’re still using the $ alias, this time it refers to the local parameter defined by the anonymous function which is initialized with a reference to the jQuery global variable. With this strategy, we’ve ended with better code which is also faster.

Now that we already have gone through the basics, we’re ready to take a look at some more advanced scenarios. Stay tuned for more.