Skip navigation

Planning to post few JavaScript pattern as series. Here goes the first basic javscript pattern: Singleton pattern. First let us see the generalised code for this pattern.

NameSpace.Singleton = (function(){

	// Private members
	var privateAttr1 = false;
	var privateAtrr2 = [1,2,3];
	function privateMethod1(){
		// code goes here
	}
	function privateMethod2(){args
		// code goes here
	}
	return {  // Public members
		publicAttr1 : true;
		publicAttr2 : 25,
		publicMethod1 : function() {
			// code goes here
		},
		publicMethod2 : function(args) {
			// code goes here
		}
	};
})();

What are the advantages of this pattern?

  • Namespacing
  • Grouping related methods and attributes together.

What are the drawbacks of this pattern?

  • Tightly coupled
  • Unit testing is difficult

For private variable in Javascript read my previous post https://vkanakaraj.wordpress.com/2009/05/07/public-privileged-static-members/

Advertisements

One Trackback/Pingback

  1. […] Rajakvk’s Blog Just another WordPress.com weblog About « JavaScript Singleton pattern […]

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

%d bloggers like this: