Simple Revealing Module Pattern Example

In this blog, I will create a simple example to demonstrate the revealing module pattern in javascript.
The revealing module pattern allows us to create a "class-like" concept in javascript. This is a useful pattern since it allows the developer to write code which is 
  • reusable
  • easy to maintain
  • provides encapsulation to avoid naming conflicts (common problem if using third party js libraries)
Let's take a look at the code first:
In this code, the variable calc can be considered like a class. calc object will have a sample property in exampleVariable and few methods like add and subtract. By default, these properties and functions are like private members so we use the return object literal to specify which members and methods are public and what should be their public names. Notice the () after the calc function definition. This signifies that this calc object will get self initialized and will be available as a singleton object. Later in the document.ready we just call the public methods on calc calc.publicAdd and calc.publicSubtract to make the calls. Here are the results:


As is visible from the code, it is reusable, easier to maintain and functions like add and subtract would not conflict with any other javascript libraries.