jQuery in Action
Functions as first-class citizens
335
When a function is declared, it has the ability to reference any variables that
are in its scope at the point of declaration. These variables are carried along with
the function even after the point of declaration has gone out of scope, closing the
declaration.
the function even after the point of declaration has gone out of scope, closing the
declaration.
The ability for callback functions to reference the local variables in effect when
they were declared is an essential tool for writing effective JavaScript. Using a
timer once again, let's look at the illustrative example in listing A.2 (the file
appendixA/closure.html).
timer once again, let's look at the illustrative example in listing A.2 (the file
appendixA/closure.html).
<html>
<head>
<title>Closure Example</title>
<script type="text/javascript"
src="../scripts/jquery-1.2.js"></script>
<script>
$(function(){
var local = 1;
window.setInterval(function(){
$('#display')
.append('<div>At '+new Date()+' local='+local+'</div>');
local++;
},3000);
});
</script>
</head>
<body>
<div id="display"></div>
</body>
</html>
In this example, we define a ready handler that fires after the DOM loads. In this
handler, we declare a local variable named
handler, we declare a local variable named
local
b
and assign it a numeric value
of 1. We then use the
window.setInterval()
method to establish a timer that will
fire every 3 seconds
c
. As the callback for the timer, we specify an inline function
that references the
local
variable and shows the current time and the value of
local
, by writing a
<div>
element into an element named
display
that's defined
in the page body
e
. As part of the callback, the
local
variable's value is also
incremented
d
.
Listing A.2
Gaining access to the environment of a function declaration
through closures
b
c
d
e