Dec 01 2008

Functions in Closures

Category: DOM, JavaScriptJonathan Fingland @ 7:47 am

I last wrote about closures and how this affects the visibility of variables and functions. This time I’m going to introduce returning functions from a closure and how it can be useful in the first part.

First off, lets say you have a strange need to create functions to consistently add a value like addFive, addTen, etc. Well this is one way to go about it.

function createAdder(addition_size) {
      return function (value) {
                     return value + addition_size;
               }
}

var addFive = createAdder(5);
var addTen = createAdder(10);

alert(addFive(3));
alert(addTen(-10));

The code above will alert 8 and 0. While this isn’t the most natural use of the technique, hopefully it is clear enough. addition_size is retained by the addFive and addTen functions because the function had visibility when it was declared.

One handy way to use this is when creating event handlers that need to take parameters. When adding a handler, you pass the function itself, which doesn’t provide an opportunity to add extra parameters, we can get around this by doing:

function getValuePlusFiveDisplayer(value) {
  return function (event) {
    var sum = addFive(value);
    alert(value + " + 5 = " + sum);
  }
}

var number_1 = document.getElementById("number_1");
number_1.addEventListener("click",getValuePlusFiveDisplayer(1),false);

var number_2 = document.getElementById("number_2");
number_2.addEventListener("click",getValuePlusFiveDisplayer(2),false);

And HTML like:

<span id="number_1" class="number_button">1</span>
<span id="number_2" class="number_button">2</span>

Which would work like this:

12

Even though you’re unlikely to need this exact example, hopefully it gives you some ideas, or helps solve some problems

Tags: ,