3 ms·
They are completely orthogonal. Javascript, Lua, Scheme and others implement * first class functions, * anonymous functions, and * closures (via lexical scop
by pygy_ 14y ago
They are completely orthogonal. Javascript, Lua, Scheme and others implement
* first class functions,
* anonymous functions, and
* closures (via lexical scope),
but some languages only implement some of these features (Python, for example has limited support for anonymous functions, and Emacs Lisp used to have the first two, but not the last one).
So, in Javascript:
function outer() {
var closed_over_local = "Hey ya!"; // The variable must be a local in the parent scope.
function inner() {
alert(closed_over_local);
}
return inner;
}
foo = outer();
foo(); // Alerts "Hey ya".
Here you can see a named function that is a closure, since it closes over a local of the parent scope.
On the other hand, you can have an anonymous function that's either pure, no outer references:
[1,2,3].map(function(i) { return i*2; });
... or an anonymous function that only references globals. AFAIK, these are not closures (they don't close over variables of the parent scope).
- btipling 14y agoEmacs lisp has dynamic scoping which allows functions to modify the variables in a caller's scope, which is horrific.
- lispm 14y agoEmacs Lisp has now lexical scope. Recent Changes: * Lisp Changes in Emacs 24.1 Code can now use lexical scoping by default instead of dynamic scoping. The `lexical-binding' variable enables lexical scoping for local variables. It is typically set via a file-local variable in the first line of the file, in which case it applies to all the code in that file.