// Standard module pattern enclosure.
var module = (function(){
/* module code */
}());
// jQuery module pattern enclosure.
var module = (function($){
/* module code */
})(jQuery);
// jQuery Module definition.
var module = (function($){
// Private variable.
var privateValue = 0;
// Public functions.
function getValue()
{
return privateValue;
}
function setValue( value )
{
privateValue = value;
}
function incrementValue()
{
privateValue++;
}
// Return public functions.
return {
getValue: getValue,
setValue: setValue,
incrementValue: incrementValue
}
})(jQuery);
jQuery( document ).ready(function() {
// Use the module.
console.log( module.getValue() ); // Returns: 0
module.setValue( 5 ); // Set the value to 5
console.log( module.getValue() ); // Returns: 5
module.incrementValue(); // Increment the number
console.log( module.getValue() ); // Returns: 6
});
This pattern is a way of creating a self-contained module or library that can be accessed by other scripts.
When JavaScript executes, the module is immediately bound to a variable. This is done by wrapping the content of the module in a self-executing function which returns the module’s public functions to the variable. The module’s public functions and properties can then be accessed from the variable using the .
(dot notation property accessor) like so: module.myFunction();
.