Saturday, May 16, 2015

Javascript Closure

Closure is a feature in Javascipt that allows an inner function access variables of its parent function.  The variables will continue to exist even if the parent function has ended.  In other words, the variable act like a global variable but only accessible to the inner function but unlike a global variable, the variable could not got messing up by other sibling functions.

For example, f is a closure.

var f = ( fn() {
   var a = 0
   return fn() { return a++;}) ();


f();

The variable a will increase by 1 each time f is called and a is protected from other functions.

When the function is called, it create an activation record.  The closure will also push this activation record into its code chain.  When the function returns, the activation record will remain as it is still referenced by the closure.  (The closure will have 2 variable objects - the top is the activation record of the function and the bottom is the global object.)

No comments: