Best Practices for JQuery Namespaces + Generic Utility Functions

What are the current “rules” for implementing jQuery namespaces for hosting common utility functions?

I have several JavaScript utility methods scattered across various files that I would like to consolidate in one (or more) namespaces. What is the best way to do this?

I am currently looking at two different syntaxes, listed in order of preference:

//****************************** // JQuery Namespace syntax #1 //****************************** if (typeof(MyNamespace) === "undefined") { MyNamespace = {}; } MyNamespace.SayHello = function () { alert("Hello from MyNamespace!"); } MyNamespace.AddEmUp = function (a, b) { return a + b; } //****************************** // JQuery Namespace syntax #2 //****************************** if (typeof (MyNamespace2) === "undefined") { MyNamespace2 = { SayHello: function () { alert("Hello from MyNamespace2!"); }, AddEmUp: function (a, b) { return a + b; } }; } 

Syntax # 1 is more verbose, but it seems like it would be easier to maintain the road. I do not need to add commas between methods, and I can align all my functions.

Are there any other better ways to do this?

+7
source share
2 answers

For the record, I ended up using the first syntax:

 $(function () { //******************************** // PREDIKT NAMESPACE //******************************** if (typeof (Predikt) === "undefined") { Predikt = {}; } //******************************** // PREDIKT.TIMER NAMESPACE //******************************** if (typeof (Predikt.Timer) === "undefined") { Predikt.Timer = {}; } Predikt.Timer.StartTimer = function () { return new Date().getTime(); }; Predikt.Timer.EndTimer = function () { return new Date().getTime(); }; }); 
+1
source

For jQuery plugins, such a template should use $.fn.myPlugin if you want it to be available for elements, and $.whatever if you just want to use a namespace. I recommend reading the official Plugin Creation Document and these articles .

But aside from jQuery, the easiest way to name your utils namespace would be as follows:

 var utils = window.utils || {}; utils.method = function(){}; 

The basics of the namespace in JS haven't changed lately - you should check out the snook article , DED's elegant approach and this SO question .

The main advantage of using a self-starting function to declare namespaces is that you can execute the file privately before returning the object. In addition, the object will be ready to autocomplete your console, which you will skip in the $ namespace because jQuery returns a function, not an object.

+3
source

All Articles