user1019031 user1019031 - 1 year ago 90
Javascript Question

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?

Answer Source

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); };
  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 :-)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download