jQuery and other libraries - name clashes.

Browser scripting
KBleivik
Site Admin
Posts: 178
Joined: Tue Sep 29, 2009 6:25 pm
Location: Moss Norway
Contact:

jQuery and other libraries - name clashes.

Postby KBleivik » Wed Jul 20, 2011 12:09 pm

The first time I read thoroughly about name spaces was in Bjarne Strostrups http://www2.research.att.com/~bs/ book http://www2.research.att.com/~bs/dne.html in the mid 1990's. That book had a whole chapter (7) on name spaces. Scope is very important in programming. Confusing the scope you operate in may introduce nasty errors. In object oriented programming, the most common scopes are
  • The global scope.
  • The function scope.
  • The class scope.

A magnitude x is different in function scope and in the global scope.
A best practice in C# is to limit the use of global variables. This doesn’t necessarily translate into a bad practice in JavaScript, but most C# developers are not aware of how easily it is to pollute the global namespace with needless variables and functions.

One way you can pollute the global namespace is to not declare your variables. In JavaScript, if you don’t declare your variables then they become globally available to the rest of the program, which is probably not what you wanted and generally a bad idea.

Source: http://enterprisejquery.com/2010/10/how ... ts-part-1/

Name spaces are not formally implemented in JavaScripts, but there are informal methods to achive the same effect to avoid name clashes:

You can follow an approach like jQuery to allow inhabiting a custom "namespace"; but this is still a design-time issue.

Source: http://stackoverflow.com/questions/8815 ... eclaration

When one or more external libraries are included in your code, the risk of name conflicts ariese. The $() factory function that is an alias for jQuery() is an exaple of a potential name clash since the $() function is fairly wide spread in other libraries. A simple way to avoid this if you use jQuery is then naturallyt to use the longer unique name jQuery() in stead of $(). Another way is to use a callback and give the jQuery object itself to it like this:

Code: Select all

jQuery(document).ready(function($) {
// Here you can use $ as usual without an external library that also use the $() function.
});

or the more compact verision

Code: Select all

jQuery(function($) {
// Here you can use $ as usual without an external library that also use the $() function.
});

so if you intend to use other JavaScript libraries http://javascriptlibraries.com/ in synch with jQuery, you may be proactive and use the above syntax in your code. The top of laziness is to do everything correct from the beginning.

Related links:
http://www.dustindiaz.com/namespace-your-javascript/

http://stackoverflow.com/questions/8815 ... er-3588712

Return to “JavaScript”

Who is online

Users browsing this forum: No registered users and 1 guest