Skip to Navigation or Skip to Content

Steve Fenton
Author of The Reason Your Website Sucks

JavaScript Name Spacing

You Are Here: Home » Blog » JavaScript Name Spacing

Feeds

RSS Feed

<< January | February | March >>

Wednesday, 3rd February 2010

This is just a quick article to demonstrate a quick bit of JavaScript name-spacing.

Why would you do this? Well, this allows you to put functions and variables inside of an identifier. It acts like a "box of stuff" and prevents variable and function name conflicts. It also supplies a neat way to organise and access your code in logical blocks.

If you're interested, here's how you do it.

Before:

  1.  
  2. var SayHello = function(name) {
  3. alert("Hello " + name + "!");
  4. }
  5. SayHello("Steve");
  6.  

After:

  1.  
  2. var MyNamespace = function() {
  3. return {
  4. SayHello | function(name) {
  5. alert("Hello " + name + "!");
  6. }
  7. };
  8. }();
  9. MyNamespace.SayHello("Steve");
  10.  

Obviously, in this example it's all a bit basic, but if you had JavaScript functions that you'd like to group together, this is a great way to do it - not a genuine name-space, but some distance towards organising your code.