How would I then create a new instance of MyModule
in this example?
In your example you cannot create an instance of your module because it is a plain object.
Are modules meant to be instantiated?
Most aren't meant to be but it's up to you if your module should be instantiated first in order to use it.
What's the proper way to instantiate an object using the Module Pattern?
Classes can be 'emulated' in javascript like this:
var MyClass = (function(){
function MyClass() {
}
var privateMethod = function() {};
MyClass.staticMethod = function() {};
MyClass.prototype.instanceMethod = function() {};
return MyClass;
}());
var classInstance = new MyClass();
And modules or namespaces like this, just as in your example:
var MyModule = (function(){
var MyClass = (function(){
function MyClass() {
}
var privateMethod = function() {};
MyClass.staticMethod = function() {};
MyClass.prototype.instanceMethod = function() {};
return MyClass;
}());
return {
MyClass: MyClass
};
}());
var classInstance = new MyModule.MyClass();
These are very simple examples but this pattern can be very complex. Like this other example of a module that you must instantiate in order to use its classes:
var MyModule = (function() {
/** Module constructor */
function MyModule(arg0, arg1) {
this.MyClass = (function() {
/** Class constructor */
function MyClass() {
this.publicArg0 = arg0;
this.publicArg1 = arg1;
}
var privateMethod = function() {};
MyClass.staticMethod = function() {};
MyClass.prototype.instanceMethod = function() {};
return MyClass;
}());
};
return MyModule;
}());
var moduleInstance = new MyModule('#some', 1324);
var classInstance = new moduleInstance.MyClass();
console.log(classInstance.publicArg0) // "#some"
console.log(classInstance.publicArg1) // "1324"