I was reading Object Oriented Javascript and found the concept of closures. I didn't quite understand why and when it is used. Do other languages like Java also have closures? I basically want to understand how knowing the concept of closures can help me improve my coding.
A closure is a scoping technique. Java does not have closures.
In javascript you can do something like that following:
var scope = this;
var f = function() {
scope.somethingOnScope //scope is 'closed in'
}
if you then do something like pass f to a function, scope is the scope of where it was defined.
Closures are know by various names in various languages but the essential points are as follows:
To create closures you need a language where the function type is a 1st class citizen i.e. it can be bound to a variable and passed around like any old string, int or bool.
You also need to be able to declare functions inline. In javascript you can do something like this:
foo("bar", "baz" function(x){alert("x")});
To pass a anonymous function as a parameter to the foo function. We can use this to create a closure.
Closures "close over" variables so can be used to pass scoped variables around. Consider this example:
function foo(){
var spam = " and eggs";
return function(food){alert(food + spam)};
}
var sideOfEggs = foo();
The side of eggs now contains a function which appends " and eggs" to whatever foodstuff it is passed. The spam variable is part of the foo function scope and would have been lost when the function exited, except that the closure "closed over" the namespace preserving it as long as the closure remains in memory.
So we're clear on closures having access to their parent's private scoped variables right? So how about using them to simulate private access modifiers in javascript?
var module = (function() {
var constant = "I can not be changed";
return {
getConstant : function() { //This is the closure
return constant; //We're exposing an otherwise hidden variable here
}
};
}()); //note the function is being defined then called straight away
module.getConstant(); //returns "I can not be changed"
module.constant = "I change you!";
module.getConstant(); //still returns "I can not be changed"
So what's happening here is we're creating and immediately calling an anonymous function. There is one private variable in the function. It returns an object with a single method which references this variable. Once the function has exited the getConstant method is the sole way of accessing the variable. Even if this method is removed or replaced it will not give up it's secret. We have used closures to achieve encapsulation and variable hiding. For a more thorough explanation of this see http://javascript.crockford.com/private.html
Java does not have closures (yet). The closest it has are anonymous inner classes. However to instantiate one of these inline you have to instantiate an entire object (usually from an existing interface).The beauty of closures is they encapsulate simple, expressive statements which is somewhat lost in the noise of anonymous inner classes.
Closure is a very natural feature that allows free-variables to be captured by their lexical environment.
here's an example in javascript:
function x() {
var y = "apple";
return (function() {
return y;
});
}
function x returns a function. note that when a function is created variables used in this function are not evaluated like when we return an expression. when the function is created it looks to see what variables are not local to the function (free). It then locates these free variables and ensures they are not garbage collected so that they can be used once the function is actually called.
In order to support this feature you need to have first-class functions which java does not support.
Note this is a way we can have private variables in languages like JavaScript.
A closure is a first class function with bound variables.
Roughly that means that:
- You can pass the closure as a parameter to other functions
- The closure stores the value of some variables from the lexical scope that existed at the time that is was created
Java doesn't have closures, although it's fairly common in Java to simulate them using anonymous inner classes. Here's an example:
import java.util.Arrays;
import java.util.Comparator;
public class StupidComparator {
public static void main(String[] args) {
// this is a value used (bound) by the inner class
// note that it needs to be "final"
final int numberToCompareTo=10;
// this is an inner class that acts like a closure and uses one bound value
Comparator<Integer> comp=new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
int result=0;
if (a<numberToCompareTo) result=result-1;
if (b<numberToCompareTo) result=result+1;
return result;
}
};
Integer[] array=new Integer[] {1,10, 5 , 15, 6 , 20, 21, 3, 7};
// this is a function call that takes the inner class "closure" as a parameter
Arrays.sort(array,comp);
for (int i:array) System.out.println(i);
}
}