Reputation: 37
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
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