Closures

12 01 2011

JavaScript functions are a combination of code to be executed and the scope in which to execute them. This combination of code and scope is known as a closure in the computer science literature. All JavaScript functions are closures. These closures are only interesting, when a nested function is exported outside the scope in which it is defined. When a nested function is used in this way, it is often explicitly called a closure.

See below for example. The loop continues until i is 5, which is the last value of i before the function addLinks exits. Then, whenever the onclick event is actually being triggered, it takes the last value of i.

function addLinks () {
  for (var i=0, link; i<5; i++) {
    link = document.createElement("a");
      link.innerHTML = "Link " + i;
      link.onclick = function () {
        alert(i);
      };
     document.body.appendChild(link);
  }
}
window.onload = addLinks;

Using closure to get expect result:

function addLinks () {
  for (var i=0, link; i<5; i++) {
    link = document.createElement("a");
    link.innerHTML = "Link " + i;
    link.onclick = function (num) {
      return function () {
        alert(num);
      };
    }(i);
    document.body.appendChild(link);
  }
}
window.onload = addLinks;
About these ads

Actions

Information

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s




Follow

Get every new post delivered to your Inbox.

%d bloggers like this: