Fri, 19 Nov 2010

8:45 PM - Anonymous functions vs closures

I've been a bit confused by anonymous functions versus closures.  Many references use them interchangeably.  They're different concepts.

An anonymous function is like a regular "named" function typically.  Some languages put limitations on them, but most of the time they're just like regular functions.

a = function() { 

return 1;

}

This isn't useful, but it's an anonymous function assigned to the variable a.  It can be helpful for event driven programming in javascript and other languages or any type of callback.

In contrast, a closure is just a function that has access to the parent environment.  Basically, you can access variables in the parent namespace. These variables are called free variables.

function hello() {

var x = 1;    

    function world() {

         return x + 2;

    }

return world();

In this case, a call to hello returns 3.  

You can also combine the two which is what most people do:

 

function outer(y) {

    a = function (z) {

           return z+y;

    }

   return a(3);

}

outer(4); // returns 7

Finally, I should mention anonymous functions are sometimes called lambda.

 

tags: anonymous lambda closures function

()