The Revealing Module Pattern

优点

  • Cleaner approach for developers
  • Supports private data
  • Less clutter in the global namespace
  • Localization of functions and variables through closures
  • The syntax of our scripts are even more consistent
  • Explicitly defined public methods and variables which lead to increased readability

缺点

  • Private methods are unaccessible
  • Private methods and functions lose extendability since they are unaccessible (see my comment in the previous bullet point)
  • It's harder to patch public methods and variables that are referred to by something private
var MyModule = ( function( window, undefined ) {

  function myMethod() {
    alert( 'my method' );
  }

  function myOtherMethod() {
    alert( 'my other method' );
  }

  // explicitly return public methods when this object is instantiated
  return {
    someMethod : myMethod,
    someOtherMethod : myOtherMethod
  };

} )( window );

//  example usage
MyModule.myMethod(); // undefined
MyModule.myOtherMethod(); // undefined
MyModule.someMethod(); // alerts "my method"
MyModule.someOtherMethod(); // alerts "my other method"

results matching ""

    No results matching ""