jQuery in Action

336
APPENDIX
JavaScript that you need to know but might not!
Prior to running this example, if we were unfamiliar with closures, we might
look at this code and see some problems. We might surmise that, because the call-
back will fire off three seconds after the page is loaded (long after the ready han-
dler has finished executing), the value of
local
is undefined during the execution
of the callback function. After all, the block in which
local
is declared goes out of
scope when the ready handler finishes, right?
But on loading the page and letting it run for a short time, we see the display
as shown in figure A.5.
It works! But how?
Although it is true that the block in which
local
is declared goes out of scope
when the ready handler exits, the closure created by the declaration of the func-
tion, which includes
local
, stays in scope for the lifetime of the function.
NOTE
You might have noted that the closure, as with all closures in JavaScript,
was created implicitly without the need for explicit syntax as is required in
some other languages that support closures. This is a double-edged sword
that makes it easy to create closures (whether you intend to or not!) but
can make them difficult to spot in the code.
Unintended closures can have unintended consequences. For exam-
ple, circular references can lead to memory leaks. A classic example of
this is the creation of DOM elements that refer back to closure variables,
preventing those variables from being reclaimed.
Figure A.5 Closures allow callbacks to access their environment even if that
environment has gone out of scope.


Другие страницы

 
Cкачать книги бесплатно без регистрации в электронном виде (pdf, chm, txt).Вы можете читать книги онлайн на нашем сайте литературного портала книг.Большая подборка учебников, пособий, интересных книг.Электронные книги на английском языке скачать бесплатно без смс.