JavaScript local alias pattern
- by Bertrand Le Roy
Here’s a little pattern that is fairly common from JavaScript developers but that is not very well known from C# developers or people doing only occasional JavaScript development. In C#, you can use a “using” directive to create aliases of namespaces or bring them to the global scope: namespace Fluent.IO {
using System;
using System.Collections;
using SystemIO = System.IO;
In JavaScript, the only scoping construct there is is the function, but it can also be used as a local aliasing device, just like the above using directive:
(function($, dv) {
$("#foo").doSomething();
var a = new dv("#bar");
})(jQuery, Sys.UI.DataView);
This piece of code is making the jQuery object accessible using the $ alias throughout the code that lives inside of the function, without polluting the global scope with another variable.
The benefit is even bigger for the dv alias which stands here for Sys.UI.DataView: think of the reduction in file size if you use that one a lot or about how much less you’ll have to type…
I’ve taken the habit of putting almost all of my code, even page-specific code, inside one of those closures, not just because it keeps the global scope clean but mostly because of that handy aliasing capability.