Tasty Technology! By Tim Scarfe. Sunday, November 26, 2006 - 19:22 [#]
Scoping in JavaScriptOmar posted a few weeks back about when this is not this. i.e. In the anonymous function; "this" will refer to global scope. His solution was this: I sent him a mail about this and may as well spread the love! In the DHTML world of past, this was always the solution. JS is a very advanced language and supports higher order functions/closures. Important to note that in JS the "." (dot/period) symbol sets the scope therefore any function run from a setTimeout etc will run in global scope (by definition). In Omar's example, one function still ran in global scope (highlighted): I liked his solution though; typically I may have done something like this: The problem with closures and DHTML is you inevitably get circular references on DOM objects and your memory usage goes sky high i.e. they are best avoided by using some reference cache and not bothering about scope. Erik Arvidsson is the world authority on this stuff (@webfx.eae.net) (plug). From JavaScript: The Definitive Guide, 5th Edition (David Flanagan): 8.8.4.2. Closures and memory leaks in Internet Explorer Microsoft's Internet Explorer web browser uses a weak form of garbage collection for ActiveX objects and client-side DOM elements. These client-side objects are reference-counted and freed when their reference count reaches zero. This scheme fails when there are circular references, such as when a core JavaScript object refers to a document element and that document element has a property (such as an event handler) that refers back to the core JavaScript object.
This kind of circular reference frequently occurs when closures are used with client-side programming in IE. When you use a closure, remember that the call object of the enclosing function, including all function arguments and local variables, will last as long as the closure does. If any of those function arguments or local variables refer to a client-side object, you may be creating a memory leak. A full discussion of this problem is beyond the scope of this book.
See http://msdn.microsoft.com/library/en-us/IETechCol/dnwebgen/ie_leak_patterns.asp for details. Copyright Tim Scarfe © 1999-2006. All rights reserved. |