Nov 24, 2008

Closure in javascript

I have read a book "Pro JavaScript Techniques", inside it define closure as follow.

Closures are means through which inner functions can refer to the variables present in their outer enclosing function after their parent functions have already terminated.

While it is correct, but if we understand the parent functions as a constructor it is easier. Here is my understanding, closure is feature that we can create a local variable in a constructor, and that variable can be accessed by the created object internally, but it can not be accessed externally. what is unique is that the local variable stay inside a hidden area in the created object. Here is a simple code to demo this.

 function Animal(name) {
     var r = {};
     var local_variable = name;
     r.say = function() { alert(local_variable); }
     return r;

 var a = new Animal("jeff");
 a.say(); //alert "fred"
 alert(a.local_variable); //undefined

If we don't need an object, we just need a function, we can even simplify it like below. In the constructor, name is local variable, the created object is function, this local varible is saved in a hidden area in the function.

function createAlert(name) {
    return function() { alert(name); }

var say = createAlert("hello");

Closure has another use. Hide the global variable. In the example below, we can have a global variable, it pollutes the environment.

var name = "hello";
function say() { alert(name); }

Now we change to use closure like below.

(function() {
        var name = "hello";
        this.say = function() { alert(name) };

// or
(function(name) {
        this.say = function() { alert(name) };


At first look, this seems more complicated. we have defined anonymous function, and run the function immediately. This function define a "say" function, and say function reference a local variable. And this variable is not global variable. The benefit of closure is not straight forward here, but it is very important in javascript framework development, because it will cornerstone for encapsulation.