Tuesday, May 1, 2012

JavaScript Fun Part 2: Closure

What is closure?

Closure is basically leveraging variable scoping in JavaScript to privatize functions and variables used within another function. In other words, a function that creates another function and returns it. But understanding the scope of your variables in JavaScript, and how you can use that scoping, makes JavaScript a much more powerful tool.

A Small Example Of Closure

var globalVar = 'something'; //available everywhere.

//a class foo (available everywhere)
var foo = function () {
   // a method only available inside our class.
   var privateMethod = function (a) {

   // returning a function creates a closure,
   // enclosing all of the private variables and
   // functions inside of the returned function reference.
   return function (b) { 
      // a variable only available inside this function.
      var prefix = 'OMG: ';
      //alert 'OMG: b'.

var closureFoo = foo(); 

//should alert "OMG: HI WORLD!"
closureFoo('HI WORLD!');

As you can see in the example above, using closure, you can hide a function of variable from some outer scope that is being used by another function. Generally, I would use something like this in more of a command pattern sort of way. Where I need to create some complicated command I needed to execute over and over again, or that may even need to maintain state on itself.

No comments:

Post a Comment

This form allows some basic HTML. It will only create links if you wrap the URL in an anchor tag (Sorry, it's the Blogger default)