Last active
August 29, 2015 14:08
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
( 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