I am trying to understand the JavaScript Module Pattern. I\'ve seen examples of what it should look like, but I don\'t understand how to use it.
For example, a few thing
The revealing module pattern is used like this:
var moduleName = (function () {
var privateVariable = 'private';
var privateMethod = function () {
alert('this is private');
};
// this is the "revealed" part of the module
return {
publicVariable: 'public',
publicMethod: function () {
alert('this is public');
}
};
}());
You can also define the public variables/methods as privates and then expose a reference to them, making them public. This is a matter of preference.
In your example, if you wanted addMessage
to be part of the module, you would do it like this:
var moduleName = (function () {
// this becomes public due to the reference exposure in the return below
var addMessage = function () {
// do whatever
};
// this is the "revealed" part of the module
return {
addMessage: addMessage
};
}());
moduleName.addMessage();