JavaScript Module Pattern - Its Time to do It

JavaScript Module Pattern is the "Number One" methodology, when I want to create big JS modules with strong logic in short time.

Why Modules? - Its simple to understanding, easy to use and inheritance, no any of this or prototype using. You can pass modules variables between from one module to another - you will see that below in this post, but now lets do some simple module practice.

What you must to know for work with JavaScript Modules

Before we will be start making of our simple modules, I want to test your skills by simple understanding of some JS conceptions. Yeah modules are easy, but they use some of the best JS practice and that make them logic so great.

JavaScript

Aha! You want to understand modules but don't familiar with JavaScript? I hope what is, but if not google will help you.

JavaScript Scopes

Scopes in JS create new scope of workspace or, in other words, variables visibility scope. To define new scope wrap your code in () symbols.

You may saw it in jQuery or other JS libs.

$(function(){  })

Anonymous functions

That's function without name, for example:

function (a){ alert(a) }

Now you may ask "W*f? How can I call it without any name?" )) You can pass anonymous function to variables or class properties (or other function buy the way).

var log = function (a){ console.log(a) }
  log('hello world')

Self invoke functions

This is simple function wrapped in scope and self invoked. Here is simple example of it:

(function(){ console.log("Hello World") })()

So when this code was loaded on client's browser, it will be executed without any call.

And more - you can send variables (or even modules) to self invoke function.

// send variable
  (function(t){ console.log(t) })("Hello World")
  // or objects
  (function(w,jq){ jq('body').prepend('Hello') })(window, jQuery)

That's was all what you need to know for successful module pattern practice) So, now nothing more can't stop us to create JavaScript modules - so let's do them!

What is JavaScript Module

Module its self invoke anonymous function with unique namespace. Yeap, many strong words) but module that's all what you saw before, but now together!

var Module = (function(){
    // interesting code here
  })()

That was basic module, but now lets see what is inside of JavaScript modules and how to use than power.

How modules store data

If you can see - all module is a function, so it we are inside function - we can return any what need: object, string, bool value, window or this reference. I will use object. Inside on this object my module will store data and methods.

var Basket = (function(){

    // module main object
    var obj = {
      name: 'Basket of customer',
      list: { },
      add: function(){ alert('add of a new item') },
      remove: function(){ alert('removing of added item') }
    }

    // return object
    return obj
  })()

Here you can see how I create Basket module with two properties and two methods. Now I can call all what store inside obj by using Basket variable:

Basket.add()
console.log(Basket.name)
Basket.list.potato = {
  weight : 2,
  sum : 1.25
}

So smart and so simple, but lets see more module tricks, which wait for us!

Private and Public Module Methods

You can see public module method - Basket.add(). Its named as public, because I can call it outside of my module. But modules can store private methods and lets create it:

var Basket = (function(){

    // module main object
    var obj = {
      name: 'Basket of customer',
      list: { },
      add: function(){ alert('add of a new item') },
      remove: function(){ alert('removing of added item') }
    }

    // private method
    function log(){
      console.log('This is private method')
      console.log(obj.name)
    }

    // return object
    return obj
  })()

So, now if you try run Basket.log() - browser will display error Uncaught TypeError: Basket.log is not a function, because this is function defined inside Basket scope, so you can't access to them from global scope, and it's mean, log() is a private method of Basket module.

But we can call it from our public methods, for example:

var Basket = (function(){

    // module main object
    var obj = {
      name: 'Basket of customer',
      list: { },
    }

    // public method
    obj.info = function(){
      log()
    }

    // private method
    function log(){
      console.log('This is private method')
      console.log(obj.name)
    }

    return obj
  })()

  Basket.info()

Here is an alternative method to organize your modules structure:

var Basket = (function(){

    function log(){
      console.log('This is private method')
      console.log(obj.name)
    }

    return {
      name: 'Basket of customer',
      list: { },
      info: function(){
        log()
      },
      hello:function(){ console.log('world') }
    }

  })()

There is no big difference between this two ways to define module structure. I use first variant when my module store 10-20 methods and its hard for me - wrap it in one object together. But if my module its 40 lines of code - why not second method?

Conclusion But not the End

So, JavaScript Modules its real great way for creating strong-logic code. And now you know how to do it, but this is not finish yet - I want to show you some interesting tricks, which you can do with your modules. Will see in the next post.

Thanks for reading and lets do JavaScript!

Source: