I’ve got the first file in my code directory as follows
myNamespace.js
var myNamespace = {};
Then my subsequent files can look as one of the two following ways.
first
(function (ns) {
ns.DoStuff = function(){
// do stuff
}
})(myNamespace);
second
myNamespace.DoStuff = function(){
//do stuff
}
So what is the difference between these two methods? Both seem to work for me. Is there a more generally accepted convention?
sorry, still new to javascript
You have an error in your first one, you’ve used
thiswhere I’m pretty sure you meantns:Leaving that aside, your first approach tends to be better because you’ve created a nice little scoping function for yourself, which allows you to have private data and functions available to all of the public methods you create on your namespace, without making them globals. E.g.:
I like doing it that way partially because I have thing against anonymous functions, and so I wouldn’t define
DoStuffas above, but rather like this:Now the function I’ve assigned to
myNamespace.DoStuffhas a proper name, which helps me out when I’m debugging my code. But that name doesn’t pollute the global namespace, which helps me stay sane and avoid conflicts with other code.