Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding closure in Javascript

I'm trying to wrap my head around closures in Javascript.

Here is an example from a tutorial:

function greeter(name, age) {
  var message = name + ", who is " + age + " years old, says hi!";

  return function greet() {
    console.log(message);
  };
}

// Generate the closure
var bobGreeter = greeter("Bob", 47);

// Use the closure
bobGreeter();

The author said that this is an effective way of using closure to make private variables, but I don't get the point.

Could someone enlighten the benefits of coding like this?

like image 618
never_had_a_name Avatar asked Oct 11 '10 01:10

never_had_a_name


4 Answers

A closure is a pair of a function and the environment in which it was defined (assuming lexical scoping, which JavaScript uses). Thus, a closure's function can access variables in its environment; if no other function has access to that environment, then all of the variables in it are effectively private and only accessible through the closure's function.

The example you provided demonstrates this reasonably well. I've added inline comments to explain the environments.

// Outside, we begin in the global environment.
function greeter(name, age) {
  // When greeter is *invoked* and we're running the code here, a new
  // environment is created. Within this environment, the function's arguments
  // are bound to the variables `name' and `age'.

  // Within this environment, another new variable called `message' is created.
  var message = name + ", who is " + age + " years old, says hi!";

  // Within the same environment (the one we're currently executing in), a
  // function is defined, which creates a new closure that references this
  // environment. Thus, this function can access the variables `message', `name',
  // and `age' within this environment, as well as all variables within any
  // parent environments (which is just the global environment in this example).
  return function greet() { console.log(message); };
}

When var bobGreeter = greeter("Bob", 47); is run, a new closure is created; that is, you've now got a new function instance along with the environment in which it was created. Therefore, your new function has a reference to the `message' variable within said environment, although no one else does.

Extra reading: SICP Ch 3.2. Although it focuses on Scheme, the ideas are the same. If you understand this chapter well, you'll have a good foundation of how environments and lexical scoping work.

Mozilla also has a page dedicated to explaining closures.

like image 86
ide Avatar answered Sep 20 '22 11:09

ide


The purpose of a closure is so that the variables you use inside a given function are guaranteed to be "closed" which means they do not depend on external variables - they only depend on and use their arguments. This makes your Javascript methods closer to a pure function, that is, one that returns the same value for the same given arguments.

Without using closures, your functions will be like Swiss cheese, they will have holes in them. A closure plugs up those holes so the method doesn't depend on variables higher in the scope chain.

Now, up until this point, my answer has been simply about organizing your code and style. So take this simple example. At the line with the comment, I invoke a function and the value of the variable a is captured for future use.

var a = "before";
var f = function(value) {
    return function()
    {
      alert(value);
    }
} (a); //here I am creating a closure, which makes my inner function no longer depend on this global variable
a = "after";

f(); //prints "before"

Now, why would you need to do this? Well, here's a practical example. Consider the following code that uses jQuery to add 5 links to the document. When you click a link, you would expect it to alert the number associated with the link, so clicking the first you would think would alert 0, and so on. But, this is not the case, each link will alert the value of 5. This is because the function I define depends on the variable i which is being modified outside the context of the function. The function I pass into bind is a Swiss cheese function.

for (var i = 0; i < 5; i++)
{
    var a = $('<a>test link</a>').bind('click', function(){
        alert(i);
    });
    $(a).appendTo('body');
}

Now, let's fix this by creating a closure so each link will alert its correct number.

for (var i = 0; i < 5; i++)
{
    var fn = function (value) {
        return function() {
            alert(value);
        };
    } (i); //boom, closure
    var a = $('<a>test link</a>').bind('click', fn);
    $(a).appendTo('body');
}
like image 25
wsanville Avatar answered Sep 23 '22 11:09

wsanville


I don't think this is a good example for private variables, because there are no real variables. The closure part is that the function greet can see message (which is not visible to the outside, hence private), but it (or anyone else) is not changing it, so it is more of a constant.

How about the following example instead?

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

var a = make_counter();
console.log(a());  // 1
console.log(a());  // 2
var b = make_counter();
console.log(b());  // 1
console.log(a());  // 3
like image 37
Thilo Avatar answered Sep 19 '22 11:09

Thilo


A better example may be

function add(start, increment) {
  return function() {
      return start += increment;
  }
}

var add1 = add(10, 1);

alert(add1()); // 11
alert(add1()); // 12

Here, every time you call the returned function, you add 1. The internals are encapsulated.

The returned function still has access to its parents variables (in this case, start and increment).

On a lower level of thinking, I think it means that the function's stack is not destroyed when it returns.

like image 30
alex Avatar answered Sep 22 '22 11:09

alex