The Revealing Module Pattern

This pattern is the same concept as the module pattern in that it focuses on public & private methods. The only difference is that the revealing module pattern was engineered as a way to ensure that all methods and variables are kept private until they are explicitly exposed; usually through an object literal returned by the closure from which it’s defined. Personally, I like this approach for vanilla JavaScript as it puts a clear emphasis on both the intent of the developer and the module itself.

“I’ve used this pattern on projects ranging from 100 to 100,000 lines of code.” – Bob Holt

This article is part of a series called JavaScript Design Patterns.




1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
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"

This pattern can also be implemented using a privately shared cache (see Example 2 of the module pattern for an example.)

Additional Resources–The-Revealing-Module-Pattern

Other Common JS Patterns

The Module Pattern
The Revealing Module Pattern
The Singleton Pattern
The Observer Pattern
The Mediator Pattern
The Prototype Pattern
The Facade Pattern
The Factory Pattern

2 responses!

JavaScript应用设计模式 | 游侠博客 said: (4 months ago) Reply

[…] 揭示模块模式 […]

Nicolas said: (4 months ago) Reply

Can you give an example with code regarding the disadvantages of the revealing module pattern. I don’t think I get it. Won’t you have the same problems with a common module ? I’m reading Addy Osmany’s book and it does’t clarifies it.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>