I am learning javascript and I came across the following code snippet:
var outerValue = true;
function outerFn(){
assert( outerFn && outerValue, "These come from the closure." );
}
Insofar as I understand closures in the above context, they allow the outerFn to actually see the outerValue variable.
My question then is: how is this any different from any other programming language – such as java for instance? It is just expected that outerValue’s scope will allow outerFn to see it.
added later on:
var outerValue = true;
function outerFn() {
console.log(outerValue);
}
function anotherFunction(arg){
console.log("anotherFunction");
arg.call(this);
}
anotherFunction(outerFn);
Is this then a better example of a closure?
Your example does not really illustrate the difference, as you do not define the scope of outerValue. In Javascript, you may nest functions arbitrarily within one another, and closures make sure that inner functions can see outer functions even when invoked after the outer functions are no longer in scope.
In java, nesting functions is not (yet) legal, and thus closures do not even come into play. Having a class field in place of
outerValueand a class method in place of your function is different, as the field of course is associated with the scope of the class, not the method.