Confused by closures in JavaScript

Possible Duplicate:
How do JavaScript closures work?
Javascript closures and side effects in plain English? (separately)

I'm new to JavaScript but I'm really confused by how closures work. Can someone explain in layman's terms what they are or why they are useful?


Closures are something like the context of a function when it is defined. Whenever a function is defined, the context is stored, and even if the 'normal' life cycle of your function is over, if you keep a reference to an element defined whithin your function execution, it can still access to elements of the context (closure), which is actually the scope of your function in its definition. Sorry for my bad english, but probably this example will make you understand:

function test() {
  var a = "hello world";
  var checkValue = function() { alert(a); };
  checkValue();
  a = "hi again";
  return checkValue;
}

var pointerToCheckValue = test();  //it will print "hello world" and a closure will be created with the context where the checkValue function was defined.
pointerToCheckValue(); //it will execute the function checkValue with the context (closure) used when it was defined, so it still has access to the "a" variable

Hope it helps :-)


If you start with a simple use, which I got from http://ejohn.org/apps/learn/#49

var num = 10; 

function addNum(myNum){ 
  return num + myNum; 
} 

assert( addNum(5) == 15, "Add two numbers together, one from a closure." );

What is happening is that the variable num is trapped (enclosed) within the addNum function.

Where this becomes handy is if you have something (this is not expected to run properly) like this:

for(var t = 0; t < 5; t++) {
  var elem = document.getElementById('mydiv' + t);
  elem.onclick = function(e) {
     alert(t);
  };
};

This should show the value 5 for every div that was set with this event handler.

If you enclose that instance of the counter within your event handler then it can be different for each one, which is the expected behavior.

This is a pretty advanced topic. Once you get more comfortable with javascript you may want to see about learning it at that point.


I strongly recommend the following article . I found it to be a great starting point for understanding closures.

链接地址: http://www.djcxy.com/p/83010.html

上一篇: 承诺jQuery中的变量范围

下一篇: 被JavaScript中的闭包困惑