Singleton Pattern – Javascript

Posted: June 23, 2011 in Design Patterns, Javascript
Tags: ,

var singleton = function () {
var privateVar = 10;
function privateMethod1() {
return privateVar;
}

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

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