You can either declare them in the original object like you did here:
var MyNamespace = {
helloWorld: function() {
console.log('hi!');
},
goodbyeWorld: function() {
console.log('I <3 Titanic');
}
}
MyNamespace.helloWorld();
MyNamespace.goodbyeWorld();
Or, you can declare the namespace and then add the methods afterwards like this:
// declare namespace object
var MyNamespace = {};
// add methods to the namespace
MyNamespace.helloWorld = function() {
console.log('hi!');
};
MyNamespace.goodbyeWorld = function() {
console.log('I <3 Titanic');
};
MyNamespace.helloWorld();
MyNamespace.goodbyeWorld();
This lets you add methods to the namespace in different places or even in different source files.
And, if you want to have some private, but static variables, you can use an IIFE (immediately invoked function expression) to encapsulate those variables like this:
var MyNamespace = (function() {
var privateCntr = 0;
return {
getUniqueCnt: function() {
return ++privateCntr;
},
goodbyeWorld: function() {
console.log('I <3 Titanic');
}
};
})();
var uniqueID = MyNamespace.getUniqueCnt();
MyNamespace.goodbyeWorld();
All three options accomplish the same goal. The third option gives you the option of private variables (which the other two do not) and you can also use the second method to add on more methods after declaring the namespace in any of the other ways (though methods you add outside the IIFE won't have access to the private variables).
If I need any private variables, I use the third option.
If I don't have any need for private variables and I'm going to define all the methods in one place, I prefer the first option as it just seems to be more obvious what you're doing - you're declaring an object with a bunch of methods and all the methods are declared in one place.
If I'm adding methods across multiple files and don't need any private variables, I will use the second option.