beyond applications and software

JavaScript summed up #4: Namespaces

In currently popular versions of JavaScript, there’s no native concept of namspaces, like in C#, Java and Co.
But namespaces are important when it comes to larger applications and/or using third party code. You risk to have conflicts with other code (being it your own code or third party code) that is named the same. Unexpected behaviour, to say it politely, can be the result (apart from polluting the global namespace with a lot of variables is just not very nice…).
So we know we need a way to simulate namespaces in JavaScript, too.

It proves to be as simple as creating one global object that hosts all your code:

var FOCUS = {};
FOCUS.firstFunction = function(){
   // your code, not polluting the global namespace...
}

There might be situations when you don’t know if you’ve already created a certain namespace. You can check it (and create it, if it doesn’t exist, yet) easily:

if ( typeof FOCUS == 'undefined' ) var FOCUS = {};
Share this:
  • Print
  • email
  • PDF
  • Twitter
  • Digg
  • del.icio.us
  • MisterWong
  • StumbleUpon
  • Facebook
  • Netvibes
  • Google Bookmarks
  • FriendFeed
  • Mixx
  • Live
  • Ping.fm
  • Technorati
  • Yigg

1 comment

1 JavaScript summed up #4: Namespaces — puremedia { 08.27.09 at 2:45 pm }

[...] original here:  JavaScript summed up #4: Namespaces — puremedia SHARETHIS.addEntry({ title: "JavaScript summed up #4: Namespaces — puremedia", url: [...]

Leave a Comment