RobG wrote:
<snip>
var x = (function(){
// Declare a 'private' variable foo
var foo = 'foo';
return {
// 'privileged' function to modify the value of foo
setFoo : function(newFoo){
foo = newFoo;
},
// Function to show the value of foo
showFoo : function(){
alert(foo);
}
};
})();
A global variable 'x' is created with properties setFoo and
showFoo whose values are anonymous functions. It just
occurred to me that the use of 'foo' within the anonymous
functions creates a closure back to the 'outer' anonymous
function - is that correct?
Yes, the internal [[Scope]] propriety of the function objects resulting
from the evaluation of the two anonymous function expressions will
include all of the objects on the scope chain from the execution context
of the outer anonymous function, including its Activation/Variable
object.
If no such closure is created (i.e. there are no references
to properties of the outer anonymous function)
If there are no references to properties of the outer function's
execution context's Activation/Variable object then an implementation
may observe this and so not include that object on the inner function's
[[Scope]] chain, but the runtime overhead in making that observation
probably would not trade off well.
is it made available for garbage collection once the call
is finished?
I doubt it. The probability is that the Activation/Variable object will
not be garbage collected until after the function objects on who's
[[Scope]] chain it appears are themselves freed/garbage collected.
i.e. the net effect of:
var x = (function(){
return {
a : function(){},
b : function(){}
};
})();
is the same as:
var x = {};
x.a = function(){};
x.b = function(){};
and:
var x = { a : function(){}, b : function(){} };
Because there are no references to properties of the outer function's
Activation/Variable object in the first case the practical difference is
(near) zero, but I would still expected the Activation/Variable object
to be on the [[Scope]] chains of the inner function objects in the first
case. As a longer scope chain implies that Identifier resolution for
properties of the object at the end of the scope chain (the global
object) will take longer, it should be possible to determine whether
implementations do 'optimise' away the Activation/Variable object when
it is not actually being used, by timing Identifier resolution in the
situations above.
Richard.