Thursday, November 3, 2011

Javascript Patterns: The Module pattern

There are a lot of different ways to structure your Javascript code (and the most popular one remains no structure at all Glimlach). One of the most used patterns out there is the Module pattern. Instead of giving you a long explanation, let me show you a short sample:
var module=(function(){
 var helloText='Hello world'
 function sayHello(){

 return { sayHello: sayHello}; 


What’s happening inside this code?
  1. I create a JavaScript function that I immediately invoke. The result is assigned to the variable ‘module’.
  2. Inside this function I create a variable called ‘helloText’. As JavaScript uses function scope instead of block scope, this variable is available everywhere inside this function but not outside of it.
  3. I add a function ‘sayHello’, this function is also only accessible inside the ‘Module’ function.
  4. As a last step I create a new JavaScript object with a function sayHello on it that refers to the internal ‘sayHello’ function I’ve just created. This object is then returned. When I immediately invoked the function in step 1 I got the object back we’ve created with one public function ‘sayHello’.
By following this Module pattern, I can create nicely scoped functions and variables without fear for naming conflicts and without polluting the global scope.

Learn it, love it…

No comments: