First off, all I’m trying to do is to structure my javascript code properly. I’ve been told I must not have anything global. So I took the 2 types of namespaces declaration from this answer and now asking you guys for the pros and cons of each.
var namespace1 = new function () {
var internalFunction = function () {
};
this.publicFunction = function () {
};
};
var namespace2 = {
publicFunction: function () {
}
};
Also, how do i have a private function in the last one namespace2?
It depends how complex your object is. For most cases, the first method is bloated and less clear. A simple object declaration is usually much cleaner:
However, it is not possible to create private functions like this, as only functions, not object literals, create scope. Depending on your school of thought, this may not be a problem. I like to have all my methods “public”, but indicate that some of them are meant for internal use by prefixing their names with an
_. This lets you easily unit test functions intended to be “private”.At the same time, you may have meaningless temporary variables (like
i) used to initialise the namespace, which you do want to hide by using a function.Of course, the first method of using a function gives you more control, not only over private/public access, but over when the “namespace” is initialized. The example you used instantiates the namespace immediately with
new, but can also choose to do this on DOM ready, or after some AJAX has completed.