3/15/10

JavaScript Namespaces

Two variations for implementing JavaScript namespaces.
The abc namespace syntax is the simplest and useful when only public members are being wrapped.
The xyz namespace syntax can be used for public and private members.
var abc =
{
  version: '1.0',
  foo: function()
  {
    return 'abc.foo';
  }
};

var xyz = function()
{
  //private
  var _version = '2.0';
  function _foo()
  {
    return 'xyz.foo';
  }

  //public
  return {
    version: _version,  //access private var
    foo: function()
    {
      return _foo();  //access private fx
    },
    bar: function(text)
    {
      return 'xyz.bar ' + text;
    }
  };
}();  //self invoking fx

Examples
abc.foo();
abc.version;

xyz.foo();
xyz.bar('test');
xyz.version;

//output
abc.foo
1.0

xyz.foo
xyz.bar test
2.0

Object Graphs in Firebug Watch Window

A slightly modified version showing sub namespaces, eg abc.demo.foo()
var abc = {};
abc.demo =
{
  version: '1.1',
  foo: function()
  {
    return 'abc.demo.foo';
  }
};

var xyz = {};
xyz.demo = function()
{
  //private
  var _version = '2.1';
  function _foo()
  {
    return 'xyz.demo.foo';
  }

  //public
  return {
    version: _version,  //access private var
    foo: function()
    {
      return _foo();  //access private fx
    },
    bar: function(text)
    {
      return 'xyz.demo.bar ' + text;
    }
  };
}();  //self invoking fx

If you use libraries with nested namespaces, local references improve performance by minimizing member lookup.
var abcd = abc.demo;
abcd.foo();
abcd.version;

No comments:

Post a Comment