Best practices for JQuery namespaces + general purpose utility functions

Posted by Armchair Bronco on Stack Overflow See other posts from Stack Overflow or by Armchair Bronco
Published on 2010-12-28T02:41:25Z Indexed on 2010/12/28 2:54 UTC
Read the original article Hit count: 290

What are some current "rules of thumb" for implementing JQuery namespaces to host general purpose utility functions?

I have a number of JavaScript utility methods scattered in various files that I'd like to consolidate into one (or more) namespaces. What's the best way to do this?

I'm 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 down the road. I don't need to add commas between methods, and I can left align all my functions.

Are there other, better ways to do this?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about namespaces