Learning Javascript – the module pattern

// October 17th, 2012 // Development, Javascript, Web Development

A module is a self contained function, meaning that its functions and variables are private, but references to them can be returned, giving access to the internal workings via a return code block. Because of the componentisation of code, it is independently testable, can be loaded asynchronously as and when needed. What this means in human talk is described below.

The module pattern

A lot of technically rich definitions for the module pattern are out there. I however like things to be explained simply, as if a 5 year old could understand it.

Basics:

* Javascript’s variables have function scope (a variable defined in a function is not directly available from outside the function).
* Functions are data, and objects at the same time (functions can contain other functions).
* Functions can be self calling by appending a set of (). This would essentially call itself.

From the above we can see that if we define a function within a function, and set a return value of references to these functions or variables, we can create private functions and variables.

For example:

var myIncrementer = function () {
var i = 0;
function increment() {
return ++i;
}

return {
inc: increment
}

}();

So what happens here is first is that myIncrement is assigned the return value of the anonymous function, which itself is a reference to the private function of increment. when you call the inc() function, the private variable i is incremented and returned.

Now also notice something, the value saves its state too. This is called a closure. Another great thing about this pattern is that you can refer to the internals of the package directly.

Leave a Reply