D
Dmitry A. Soshnikov
<snip>
If all function objects were closures then the following program would
work:
<script type="text/javascript">
a = 42;
function f()
{ alert(a); }
delete a;
f();
</script>
But it doesn't, it says error (at least in an uptodate IE8).
No, it's still the closure, but you've reached the topic of "captured by
reference" and "captured by value". ES implementations is "captured by
reference" in respect that the parent frame is referred by the [[Scope]]
pointer. Accordingly, if something disappear in that frame, it's
reflected at reading from the closure.
Other languages (especially with immutable nature) may use "capture by
value" strategy. Some languages may probably combine both strategies.
In other languages with closures either there are no global variables or
they're accessible everywhere, always, so there is no need for a special
mechanism to capture the globals used by a function.
Yes, the global frame is always accessible, so e.g. in Python global
functions has `None` as their `__closure__` reference.
ECMAScript is different, as usual.
No so, it's completely apparent with the common theory when all
discussing here things are described long time before ES is appeared at all.
Some kinds of global variable can be
deleted and so ought to be preserved by closures.
No, and I hope now it's clear that "capture by reference" rules in this
case.
Thus, either top-level function declarations do not form closures, or
they're always empty closures.
If to take the formal definition of the spec, a global function doesn't
differ from an inner function and in the same way saves [[Scope]].
In practice, yes, there can be optimizations but this optimization is
not so big (just not to allocated the storage for the [[Scope]] pointer
itself since the global frame may always be found). However, the common
implementation IMO is a better argument to implement these functions the
same way and to put the reference to the global frame into the [[Scope]]
-- it's easier to handle functions calls in respect of identifiers
lookup, etc.
Again, by the spec all functions (except those cases with `Function`
functions) are closures. By the implementations, if a function doesn't
use free variables and doesn't use `eval` there's no need to save
[[Scope]] and all its local variables may be allocated on the stack, not
on the heap.
Dmitry.