Thursday, August 13, 2009

Groovy Closure vs. javascript closure

Coming from a javascript and java background, i've learned to use the javascript closure to its full advantage, but when we used groovy (on grails) for our new system, I was surprise that the concept of closure in groovy is different.

The definition of closure in groovy (from groovy.codehaus.org) is that, a groovy Closure is like a "code block" or a method pointer. It is a piece of code that is defined and then executed at a later point. It has some special properties like implicit variables, support for currying and support for free variables (which we'll see later on). We'll ignore the nitty gritty details for now (see the formal definition if you want those) and look at some simple examples.

GROOVY CODE:

def myclosure = { println "hello world!" }

println "Executing the Closure:"
myclosure() //prints "hello world!"



The javascript closure is a functionality that marks a variable, that it will be use later. So even when it goes out of scope, the data is saved in the memory. Here's an example:



function SayHelloTo(name) {
var greeting = 'Hello ' + name;
var display = function() { alert(greeting); }
return display;
}

var greet = new SayHelloTo("Aidan Thor");
greet();




This is simply defining a method with a local variable called "greeting" and another method inside called display, then it returns that method.

When you instantiate "SayHelloTo", and execute it ( "greet()"), you would think that it will throw an error, because "greeting" is out of scope, but actually it will not throw an error, because the method created a closure (knowing that "greeting" will be called later).