1

I have been writing an app that has become fairly Javascript intensive and am running into namespace issues.

I know there is a lot out there on this topic but I'm still a little confused as to how I should go about it.

Is there a way to wrap all my classes and object literals into a namespace and is this the best approach?

I read this post http://yuiblog.com/blog/2007/06/12/module-pattern/ and I would like to namespace my project but not sure how to go about it using normal javascript or jQuery.

edit: I understand this is not a straight forward question because its a matter of personal preference, style and requirements.

Thanks,

Tim

Tim
  • 2,235
  • 4
  • 23
  • 28

2 Answers2

2

The article pretty much sums up the use of a "namespace" object (there are plenty of other articles on the topic too). Note that you can get exactly the same effect using global variables and an underscore with the same naming scheme, so:

var myLib = {
  method1: function()...,
  method2: function()...
};

or

function myLib_metod1()...
function myLib_metod2()...

are equivalent from a "namespace" collision perspective. However, I think using an object is neater.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • Thanks Rob, I agree with you, I've been using this approach for a while but now have a bunch of object literals and after reading that article it lead me to believe I need to start wrapping them up. – Tim May 18 '11 at 01:25
2

Personally, I hate it when people wrap everything inside of a function(){} wrapper. It basically makes everything private and doesn't let you add patches properly.

You can always declare a single object in the global namespace:

var base = {
  class0:function(){}
};
base.subspace1 = {
  myVar:'foo'
};
base.class1 = function(){};

Additionally, you can append to that object dynamically, through secondary script files:

base.subspace2 = {};

Usage:

var foo = new base.class0();
var bar = base.subspace1.myVar;
John Green
  • 13,241
  • 3
  • 29
  • 51
  • Thanks John, this is a nice approach. I think I have read so much and have tried so many things that I didn't think that I can just append to any object like that. – Tim May 18 '11 at 01:22
  • No problem. The important thing to know about JavaScript is that a standard object it is really just a big hash table. Once you sort of get that, the rest comes through. You could, for instance, access bar as window['base']['subspace1']['myVar']. This would be generally analagous, though is a bit slower and considered a poorer coding style. – John Green May 18 '11 at 01:26