On 12/26/10, Angus Croll <[email protected]> wrote:
> Actually closures *do* reference every outer variable even when not
> used - if they did not, JavaScript's entire lexical scoping principal
> would break. Evey invocation of a function establishes and enters a
> new execution context. Each  execution context defines a
> VariableEnvironment which is a repository for variables declared by
> that context. In addition, each VariableEnvironment will reference the
> VariableEnvironment of its enclosing context. In this way every
> function invocation references - in the form of a hierarchy - the
> entire universe of variables to which it has access.
>
> What effect do closures have on memory leaking? Almost impossible to
> answer

The question needs to be answered on a case-by case basis. The simpler
functions, the easier this is.

since every JavaScript function in effect forms a closure -
> that is how functions reference outer variables including global
> variables. Better to not get hung up on closures and memory leaks per
> se and instead make the following checks:
>
> 1) is my code designed to work in IE7 or older?

The discussed example leaks explicitly in every browser.

> 2) Does my JavaScript make direct reference to a DOM object?
DOM objects take more memory than user-defined objects and primitives,
so the consequence of DOM object leaks are more consequential.

> 3) Does that DOM object have any attributes that reference back to my
> JavaScript (typically expando properties)
>

That is a step that can help find a different leak pattern.

That pattern uses scope, too, and I believe that a more common case
for that is not expando properties but is instead properties that
refer to the native object via event handlers, e.g.

myObj.onclick = function() {

};

where the `myObj` has a reference to the function and the function has
a reference to `myObj`, via scope.

That's a dfferent leak pattern.

I believe that your TOFU style top post reflects your style of
reading. It is hindering communications and helping to spread
misinformation. Please learn how to post so that we can avoid that!
TIA.

> If the answer to any of the above is no then you probably won't suffer
> memory leaks - so sit back, relax and take full advantage of
> closures ;-)
>

That contradicts your opening line: "Actually closures *do* reference
every outer variable even when not used". That line is correct.

[snip a fullquote under with signatures etc]
-- 
Garrett

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to