user2208533
user2208533

Reputation: 37

Can we add the same namespace for two javascript files?

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}
};

Upvotes: 0

Views: 485

Answers (1)

Brad
Brad

Reputation: 163232

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 = {} }

Upvotes: 1

Related Questions