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?
Armchair bronco
source share