Skip to content

Instantly share code, notes, and snippets.

@Stoffo
Last active August 29, 2015 14:08
Show Gist options
  • Save Stoffo/c9521077c7a06fb9d277 to your computer and use it in GitHub Desktop.
Save Stoffo/c9521077c7a06fb9d277 to your computer and use it in GitHub Desktop.
This pattern is used to mimic classes in conventional software engineering and focuses on public and private access to methods & variables. The module pattern strives to improve the reduction of globally scoped variables, thus decreasing the chances of collision with other code throughout an application.
( function( window, undefined ) {
// normally variables & functions start with a lowercase letter but with modules, that is not the case.
// The general tradition is to start them with a capital letter instead.
function MyModule() {
// `this` refers to the instance of `MyModule` when created
this.myMethod = function myMethod() {
alert( 'my method' );
};
// note that we still use a function declaration even when using a function expression.
// for more information on why, check out: http://kangax.github.io/nfe/
this.myOtherMethod = function myOtherMethod() {
alert( 'my other method' );
};
}
// expose access to the constructor
window.MyModule = MyModule;
} )( window );
// example usage
var myModule = new MyModule();
myModule.myMethod(); // alerts "my method"
myModule.myOtherMethod(); // alerts "my other method"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment