Revealing Module Pattern – Javascript

Posted: July 1, 2011 in Design Patterns, Javascript
Tags: , ,

Define all your functions and variables in the private scope and return an anonymous object at the end of the module with pointers to the private variables and functions you want to reveal as public. Check more @

http://www.wait-till-i.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/

Ex: Singleton pattern using Revealing Module Pattern

var singleton = function () {
var privateVar = 10;
function privateMethod1() {
return privateVar;
};
function SetVal1(val) {
privateVar = val;
};
function GetVal1() {
return privateVar;
};
function GetVal2() {
return privateMethod1();
};
return {
SetVal1: SetVal1,
GetVal1: GetVal1,
GetVal2: GetVal2
};
} ();

var obj1 = singleton;
var obj2 = singleton;
alert(obj1.GetVal1());
obj1.SetVal1(20);
alert(obj2.GetVal1());

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s