Using the $ Alias Without Creating Global Conflicts - J Query

Problem
You want to use the shortcut $ alias instead of typing the global name space name (jQuery) without fear of global conflicts.

Solution

The solution here is to create an anonymous self-invoking function that we pass the jQuery object to and then use the $ character as a parameter pointer to the jQuery object.
For example, all jQuery code could be encapsulated inside the following self-invoking function:

Discussion
Essentially, what is going on here is that we have passed the global reference to jQuery to a function that creates a private scope. Had we not done this and chosen to use the short hand $ alias in the global scope, we would be taking a risk by assuming that no other scripts included in the HTML document (or scripts included in the future) use the $ character. Why risk it when you can just create your own private scope?
Another advantage to doing this is that code included inside of the anonymous self invoking function will run in its own private scope. You can rest assured that anything that is placed inside the function will likely never cause a conflict with other JavaScript code written in the global scope. So, again, why risk programmatic collisions? Just create your own private scope.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics