[JavaScript] Closure

Function Closure is one of the most widely referred JavaScript techniques. It sounds complex but once you have understood the concept it becomes quite useful. Also it is not as difficult as you might think.

1. Nested Functions

Functions can be nested. Variables in JavaScript are scoped in functions and variables in outer functions can be accessed in inner functions. (Just like global variables in functions).

function outer() {
  var x = 10;

  inner();

  function inner() {
    var y = 20;
    alert(x + y);
  }
}

outer(); // call inner() and shows 30

There’s nothing new here.

 

2. Closure

Let’s change how to call the function a little bit.

function outer() {
  var x = 10;

  return function inner() {
    var y = 20;
    alert(x + y);
  }
}

var innerFunc = outer();
innerFunc(); // 30

The “innerFunc” variable refers to the inner function. When it is called, only “inner()” is invoked. Interesting thing is that “inner()” tries to access “x” that is defined in “outer()”. But you already executed “outer()”, which does not exist any more.

But the result is still 30.

Closure” means that the variable in the outer functions stay alive as long as the inner functions are alive.

 

3. Modules

You might wonder why “Closure” is an important concept in JavaScript at any rate. I think people do not use nested functions often, not to mention closures.

One example of closure is a “Module“. A module is like a class on other languages. It hides its state and exposes its interfaces.

var Calculator = function (x, y) {

  // private members
  var _x = x,
      _y = y,
      _add = function () { return _x + _y; },
      _multiply = function () { return _x * _y; };

  // public interface as an object
  return {
    add: _add,
    multiply: _multiply
  };
}

var calc = new Calculator(3, 4);
alert(calc.add()); // 7
calc = new Calculator(5, 10);
alert(calc.multiply()); // 50

By using closures, you can simulate private members (variables in outer functions) and public interfaces (inner functions).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s