HTML and CSS Reference
In-Depth Information
A common use for a closure is to set up the parameters for a function that will be
called at some time in the future. JavaScript's setTimeout() function is used to set a timer
in your program. The first argument may be a reference to a function that will be called
after some time interval has passed. You will see in future chapters that JavaScript also
uses closures with event handling and information hiding.
Douglas Crawford writes ( ), “The
pattern of public, private, and privileged members is possible because JavaScript has clo-
sures. What this means is that an inner function always has access to the vars and param-
eters of its outer function, even after the outer function has returned. This is an
extremely powerful property of the language. There is no book currently available on
JavaScript programming that shows how to exploit it. Most don't even mention it.”
On the other hand, accidentally creating closures can have harmful side effects such
as Internet Explorer memory leaks and reduced efficiency of code. A very detailed article
on both the pros and cons of using closures, written by Richard Cornford, can be found
In the following example the outer function is called paint() and the inner function
is anonymous. The paint() function receives two parameters. It then creates a local
string variable called str and assigns the parameter values to it. When paint() exits, those
variables and their values continue to exist even though they seem like they should have
gone out of scope. Why? Because the anonymous function needs access to the variables
in paint() until it has been called and exits.
<script type="text/javascript">
function paint(type, color) {
var str = "The " + type + " is " + color; //local variable
var tellme = function() { // Anonymous function
document.write("<big>"+str+".</big><br />")
return tellme ; / return a reference to the function
<body bgColor="lightgreen">
<h2>Testing a closure</h2>
<script type="text/javascript">
var say1 = paint("rose","red") ;/* A reference to the
anonymous is
function is returned */
var say2 = paint("sun", "yellow") ;
alert(say1); // See the value in say1 Figure 7.13
say1() ; // Call the anonymous function
say2() ;
Search WWH ::

Custom Search