We all know that global variable are evil. Namespacing your variables and methods is now considered a good practice and shows your awareness about the trends. Anyway, I thought how can I namespace my variables and methods in jQuery. Well, first off, I can easily extend jQuery with custom written plugins.
$.fn.extend({ myNamespaced: function(myArg){ return 'namespaced.' + myArg; } }); jQuery().myNamespaced('A'); $().myNamespaced('A'); // Shorthand $() // Outputs: namespaced.A
Now my functions are namespaced and would not conflict with any other already declared functions with the same name. This is great, but to access my functions or variables I have to call jQuery()
. The code still looks like chaining not namespacing. To declare your variables or functions in jQuery namespace you can extend the core jQuery object itself using jQuery.extend()
rather than jQuery.fn.extend()
.
$.extend({ myNamespaced: function(myArg){ return 'namespaced.' + myArg; } }); jQuery.myNamespaced('A'); $.myNamespaced('A'); // Shorthand // Outputs: namespaced.A
As you can see, now I can call my functions and properties without parenthesis after jQuery object. Now my functions have a jQuery namespace and will not conflict with other functions that might have the same name.
TIP:
Use $.extend({})
to namespace your fields and methods.