Skip to content

Instantly share code, notes, and snippets.

@carldanley
Last active April 27, 2016 14:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save carldanley/5da969fbbe2ba3f060da to your computer and use it in GitHub Desktop.
Save carldanley/5da969fbbe2ba3f060da to your computer and use it in GitHub Desktop.
Example of the Module Pattern
( 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