I would like to achieve module pattern in JS. I followed some posts in google and starting writing my own. here is what I would like to achive
mns - will be the name space for my lib
math - will be one of the sub-module in mns
and I want all these modules in separate files.
here is mns.js file code (it is just for namespace no functions in it)
var mns = (function () {
return {};
})();
here is math.js code(i want this as a submodule for mns)
var submodule = (function (mns) {
var math = (function(){
var counter = 0;
var incrementCounter = function () {
return counter++;
}
var resetCounter = function () {
alert( "counter value prior to reset: " + counter );
counter = 0;
}
})();
mns.math = math;
return mns;
})(mns || {});
I am expecting application.js will call like below
mns.math.incrementCounter();
mns.math.resetCounter();
Right now, I am getting Cannot read property of undefined
error when calling incrementCounter & resetCounter.
Please guide me in this.
All is looking good, except for the
math
module:In order to use
incrementCounter
andresetCounter
you have to return them in an object (So thatmath
will be set to something).Something like this should work: