L
Lasse Reichstein Nielsen
John G Harris said:<snip>
To sum up :
You can't insist that top-level functions form closures because there is
no evidence that they do. Equally, I can't insist that top-level
functions do not form closures in strict mode because there is no
evidence that they don't.
It's certain that the variable is looked up in the environment where
the function is created (which is the global scope). The variable
isn't dynamic scoped, i.e.:
var a = 42;
function toplevel() { return a; }
function scope() {
var a = 10;
return toplevel();
}
alert(scope()); // alerts 42.
So, in some sense, the function object is a closure (like any first-class
function in a statically scoped language). The function does remember
where to look up its variables, even if it's just remembering that the
scope is trivial.
I'm happy for you to say that top-level functions form closures,
provided you admit that this is for convenience and tidiness.
It describes what they do - but if one doesn't consider the global
object as part of the captured scope chain, but merely as an implicit
default, then top-level functions (not inside with-statements or catch
clauses) will have an empty/trivial captured environment.
I'd still call it a closure. Capturing an empty environment is
different from not capturing one at all. You can't really have first
class functions and static scope without every function value being a
closure - even if it's a trivial one.
You also need to admit that in non-strict mode closures are a little
bit broken (but in a way that will only bother the worst kind of
library).
I'll admit to that, because I don't think mutable environments are
that good an idea to begin with
/L