6/5/2013 - 5:02 PM

Javascript Module Pattern

Javascript Module Pattern

var jpm = {
    animated: true,
    openMenu: function( ) {
        // Open menu…
        this.setMenuStyle( );
    closeMenu: function( ) {
        // Close menu…
        this.setMenuStyle( );
    setMenuStyle: function( ) { /* Do something */ }

The idea is to break down code into the smallest, most reusable bits possible. I could have written just one toggleMenu( ) method, but creating distinct openMenu( ) and closeMenu( ) methods provides more control and reusability within the module.

Notice that calls to module methods and properties from within the module itself (such as the calls to setMenuStyle( )) are prefixed with the this keyword—that’s how modules access their own members.

That’s the basic structure of a module. You can continue to add methods and properties as needed, but it doesn’t get any more complex than that. After the structural foundations are in place, the reusability layer—options and an exposed API—can be built on top.