SG Dev Corner

SG Dev Corner

On programming, erlang, science, web design, business and politics.

 
 

21 February 2006 - Epigrams in Programming

Epigrams in Programming by Alan J. Perlis. Funny article from ACM's SIGPLAN publication, (September, 1982).
Comments (0) - Leave a Comment


21 February 2006 - Javascript Closures

A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).
An easier way to define closures is using the words of Paul Graham in On Lisp: "Closures are functions with local state".

Let's see a classical example:

function adder(n) {
function inner(x) {
return x+n;
}
return inner
}
Function adder takes an argument and returns a closure where the variable n is bound at the time the function is defined. So we can call adder many times and get different closures whose behaviour depends on the binding of n:
var adder2 = adder(2);
var adder10 = adder(10);
alert(adder2(5)); //alerts 7
alert(adder10(5)); //alerts 15

Closure are a powerfull and elegant tool in a programmer's toolbox. I find myself using them for a lot of different things from defining callback functions, to easy refactoring of code, define control structures, to customize function behavior by passing closures as arguments.

For me they are invaluable, so I'll be back on them soon.


Comments (0) - Leave a Comment