em*********@gma il.com wrote:
I guess what I'm trying to ask is when creating a single instance of an
object is there a downside to using closures?
Not really. The need to maintain the scope chain formed when creating
that closure will increase memory usage slightly, but it should be
negligible. If there are DOM objects referenced via that scope chain,
then there is the possibility of memory leaks in MSIE should those
references be circular, but that's not unusual and the remedy is the same.
The real question is if there are benefits to using a closure. If you're
happy with a convention to indicate private data (say, a leading
underscore), then that may be enough. On the other hand, if it would be
necessary to add properties to the global object (global variables and
functions), then it may be better to encapsulate those declarations
within the body of a function.
My understand is that when a closure is created the
Activation/Variable object is copied to the scope chain. Does this
happen for every invocation of the _get_ method?
I'm somewhat confused by what you're asking. As I see it, you're worried
that when a closure is created, extra run-time overhead is incurred when
that function is called. There isn't. The function is still called in
the usual way.
The scope chain (or more precisely, the internal [[Scope]] property) of
a function is determined when it is created. That is, when a function
declaration is parsed, or a function expression is evaluated (note the
subtle difference). For closures and inner functions, this will only
happen when the outer function is called - not at any other time.
ABC.Util.SomeOb ject = function() {
/* Note: there's no reason to use a function expression
* here.
*/
function private(val) {
return "testing";
}
return {
get : function(val) {
return private(val);
}
};
}();
During the execution of that enclosing function, the inner function
expression will be evaluated during evaluation of the object literal. It
is at this point that the [[Scope]] property for the get method is assigned.
The scope chain for any given execution context isn't actually
initialised until the function that establishes it is called. This is
because the scope chain includes the arguments passed to that function,
and these cannot be known until the call is made. At this point, the
activation object is added to the scope chain, followed by the objects
referenced by the [[Scope]] property. This occurs for any function,
whether in relation to a closure or not.
Hope that helps,
Mike
Please do not top-post when replying to this group. Moreover, please
trim quotes to include only relevant material.