Local Alias pattern

2 minute read

In any jQuery Plugin there JavaScript local alias pattern is being used as a best practice. They have localized the global jQuery object as an alias $. It is a handy and popular pattern for JavaScript developer however, that is not very well know from C# developers or fledging JavaScript people.
Local alias pattern has 3 benefits:
1)      It allows using short-cut custom name for a global namespace, thus shortening the code writings, page size decreases.
2)      It does not populates the global scope variables
3)      It allows us to make global variable to make it localize and thus faster to refer the variable.
As we know to refer the global variable is slower than to referring the local scoped variable.

[sourcecode language="javascript"]

See the below example:
(function ($) {
        $.fn.myPlugin : function(){
        …//new plugin code.
}
}
)(jQuery)

[/sourcecode]

In the above code jQuery object is being passed as an argument to the self executing function which is being aliased by $. Therefore, inside the function we can use the alias $ without any hesitation as it is referring to the jQuery object.

If we had just used $ as an alias to jQuery without passing it as an argument and bringing it inside out local scope then there would have lot of chances that in some other JavaScript library $ may be overridden by some other object or value and it might have broke our code.
In below code if you see window object is being passed as an argument.

[sourcecode language="javascript"]

(function( window, undefined ) {
//jquery code..
// Expose jQuery to the global objectwindow.jQuery = window.$ = jQuery;
}) (window);

[/sourcecode]

By passing one argument “window” while calling it, we are able to localize the window object. The second argument is not being passed therefore; the 2nd parameter would be assigned as undefined.
There is a chance that in somewhere else the undefined is assigned with some other value that may be overridden by the jQuery code therefore, in jQuery function they have made undefined as a local parameter so that they can use the undefined without worrying about the external world.
By making our object locale we are not populating the global scope with other variables.

[sourcecode language="javascript"]

namespace Rupesh.AliasDemo {
    using System;
    using System.Collections;
    using CountriesCode = Utility.Constant.Countries;

[/sourcecode]

In above code you can see that one alias has been created for Utility.Constants.Countries as CountriesCode.
So now under the Rupesh.AliasDemo namespace in each class, CountriesCode can be used as shortcut alias instead of writing the whole name (Utility.Constant.Countries).
This will make more easiness while writing the code, will save time and number of lines of code.
After knowing this I am vastly using this pattern in my C# as well as JavaScript code.