Javascript patterns headache, the path to modular applications (part 1)

by Cedric Dugas on May 19, 2010

With libraries like jQuery, manipulating the DOM, ajax calls, animating has become really trivial. The problem is, it also becomes easy to have a mess of DOM ready statements without any comments or structure.

One thing most javascript developers start to do at some point is use objects literal to structure their code. This is a start, but currently creating a front-end intensive web app, I started to wonder if I could do better.

My goal was:

  • Easy to understand
  • Modular
  • Each module will inherit a set of tools and can be instantiated
  • One namespace
  • Can apply tests or unit test from outside of the application.
  • Can use the aop plugin (aspect oriented programming) to add logs to internal functions

First, I would suggest you look at a couple of resources if you are not too familiar with javascript patterns.

Some nice stackoverflow discussions:


With this in mind, 3 patterns sticked more than the others, let’s check them all.


** I am not an expert at javascript patterns and inheritance but I think it was nice to share my findings, please feel free to discuss and correct this article in the comments if necessary.

Object Literals

Object literals are great. You get a pattern that is simple and easy to organize, everything is public, everything can be overwritten, so you don’t have to worry too much about having things you can’t access. Easy to follow and understand, even for new comers.

A typical object literal:

var module= {
	init : function() {
		module.load();
	},
 
	load : function() {
		/* instructions */
	}
};
 
/* Load Init in your script */
module.init()

The “self executing” revealing module pattern

The module pattern is a little bit more complex than a simple object literal, that being said, it gives you more power over what you want to be private and public. Basically you hide all your module behind a closure, this closure makes everything in the function private. You then use return {} to make a reference to a function you want public.

Now I will not get in the private or not debate, but I will say that some people disagree with this pattern.

var revealingModulePattern = function(){
  var privateVar = 1;
  function privateFunction(){
    alert('private');
  };
  var publicVar = 2;
  function publicFunction(){
    anotherPublicFunction();	  
  };
  function anotherPublicFunction(){
    privateFunction();
  };
  // reveal all things private by assigning public pointers
  return {
    init:publicFunction,
    count:publicVar,
    increase:anotherPublicFunction
  }
}();
revealingModulePattern.init();

As you can see, you create a public reference to the private function. That was my main problem with it. You never really have access to the public function, you just use a bridge to fire it. It creates problems when you want to bind something to a public function, it will never fire if this function is fired internally. Also, You can’t modify this object.

The module pattern, prototype style

Ahh prototype, those damn prototypes. I found this pattern gave me more liberty, and at the same time, a way to really use my public functions and not just reference them. On the question, but what is a prototype? Let’s just put it this way without going into details:

In the example below, namespace.Classname.prototype will be referenced by every instance you create with “new namespace.Classname();”. So a prototype would normally exist 1 time, if you would create 2 instances, and add a new prototype method, both instances would see it. In brief, when you create a new instance, everything in “namespace.Classname = function() {” is cloned, everything in “namespace.Classname.prototype” is not cloned, and is shared with all instances.

Here what it looks like:

var namespace = {};
namespace.Classname = function() {
    // constructor    
    function privateFunctionInit() {
        // private
    }
    this.privilegedFunction = function() {
        // privileged
        privateFunction();
    };
 privateFunctionInit() 
};
namespace.Classname.prototype.aMethod =function() {
        this.privilegedFunction();
    }
namespace.Classname.prototype.anotherMethod = function() {}
 
var class = new namespace.Classname();

Now this is really not what Crockford would advocate, but still, I found this was the pattern that was suiting best my ‘global’ needs.

Hope this helps you in your quest of modular javascript ;) . In part 2, I explain my javascript “framework”, this is really just my starting point for creating apps, or even just a website.



12 comments

Hi, thanks for nice article.
I’m looking forward to read part 2 .

by jacek_s on May 19, 2010 at 4:58 am. Reply #

I personally use the module pattern, which I found more readable.
You can also namespace it, I already did it with ExtJS, but I don’t know if it’s possible with other JS lib.

These 2 tutorials are really well explained :
http://www.extjs.com/learn/Tutorial:Application_Layout_for_Beginners
http://www.extjs.com/learn/Manual:Basic_Application_Design

by koskoz on May 20, 2010 at 3:03 am. Reply #

That’s why i love MooTools. BTW the MT Class system got recently ported to jQuery

http://moo4q.com/

by TOFU on May 22, 2010 at 4:33 pm. Reply #

Nice post. I see some js libs like SWFObject use the module pattern. I often use this one and love this too. The big benefit of this method is allowing us to create private functions and private variables.

by Rilwis on May 25, 2010 at 1:21 pm. Reply #

good post.
another great article on design patterns:
http://www.webreference.com/programming/javascript/ncz/column5/

by jojo on May 18, 2011 at 7:39 am. Reply #

Fantastic post, thank you. I simply signed up to your rss!

by Prada outlet online on July 14, 2011 at 3:09 pm. Reply #

Thanks a lot for the information which was very helpful for me. I had uploaded all images and saved the information.

by Hollister on July 17, 2011 at 11:07 pm. Reply #

. I was extremely pleased to find this website.I wanted to thank you for this good understand I definitely enjoying every single small bit of it and We’ve you bookmarked to check out new stuff you post.

by Abercrombie Fitch Milano on July 17, 2011 at 11:07 pm. Reply #

Tkanks for sharing! Very Nice!!

by Martin Lapietra on July 26, 2011 at 6:58 pm. Reply #

Javascript patterns headache, the path to modular applications (part 1) Position Absolute Pretty nice post. I just stumbled upon your weblog and wished to say that I have really enjoyed surfing around your blog posts. In any case I will be subscribing to your rss feed and I hope you write again very soon!

by Temple Run Brave Disney apk on July 5, 2012 at 5:39 am. Reply #

Nike HyperVenom Phatal Boots

by Womens Nike Air Max 2013 on February 25, 2014 at 12:13 am. Reply #

i love your blog and i think its going to my favorite!!i love viagra and cialis too! ffbdkgcggfgk

by Johnb752 on July 6, 2014 at 7:07 am. Reply #

Leave your comment

Required.

Required. Not published.

If you have one.