0

I am trying to put all my javascript function in one namespace. I have two javascript files and i am trying to put all the functions both the files into one namespace. So when i define the same namespace for both the files. The first gets over written by the second. I have defined my namespace in both the files as shown below. Is there a way i can stop this other putting all the function to one file? Thanks for the help.

var mynamespace={
foo:function(){Som code},
bar:function(){some code}
};
user2208533
  • 37
  • 2
  • 5
  • There's also RequireJS and AMD. I think I saw a [nanoloader](https://gist.github.com/pradador/218423) in JS the other day too. – Jared Farrish Mar 28 '13 at 03:11

1 Answers1

1

Yes, you can. In each file:

var mynamespace = mynamespace || {};

And then pick the next line for the file you have:

mynamespace.foo = function () {

or

mynamespace.bar = function () {

Basically, what this does is assign a current value of mynamespace to mynamespace if it exists. Otherwise, it creates a new object. Note that depending on if you declare mynamespace above or not, you might need this line up top instead:

if (typeof mynamespace === 'undefined') { var mynamespace = {} }
Brad
  • 159,648
  • 54
  • 349
  • 530