Skip to content

JavaScript Module pattern

A lot of critical voices are shouting out about the bad things the module pattern in JavaScript brings with it. Well, I am going to shout back because they are just silly stupids that doesnt know how to code. Maybe they are still living with their mom eating pizzas. Who knows. But who am I to judge about that :)

I am going to give you a brief intro to why I like this pattern and how I use it in my current project.

Simple recap:

/*global jQuery */
var MODULE = (function($this, $){
       var dividend = 20;
       $this.someNumber = 200;
       $this.someNumberDivided = function(){
            return this.someNumber/dividend;
        };
}(MODULE || {}, jQuery));

MODULE = (function($this, $){
        // More methods added to $this
}(MODULE || {}, jQuery));

This example is tested in JSLint. So it is executable.

The feature I like the most is NOT actually the private variables. When I use private variables I use them solely when those variables cannot be used with any good purpose or reason outside the module.

And, I use jQuery, so I am not dependant upon another module pattern based frameworks. When I build new sites they are now all built with the module pattern with jQuery as toolchain.

For me the module pattern gives me the following advantages:

  • Good separation of code
    • Each page can access code defined in a parent module. For this to work I have made my own submodule system.
    • General page logic is separated from specific widget/gadget logic
  • Its easy to add new methods to the main module, and, considering my spare use of private variables, they can in 90% of the usecases access what they need.
  • I can import external libraries and use them with my own naming conventions. One example is jQuery. See example above.
  • It looks pretty. I can’t get the same look and feel with Prototype JS. It doesnt make me smile to make classes. It makes me smile to make modular application code.
  • JavaScript can be loaded partially because each module can use loose agumentation.
Disadvantages? Many. But when you are coding in JavaScript or coding in general, you should be focusing on what looks readable and not necessarely what is the most efficient.
I don’t give a dangling about performance.
I let the jQuery developers care about that.
Anyone who want to bash back? :) You are certainly invited :)

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*