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 ( http://www.crockford.com/JavaScript/private.html ), “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
at http://www.jibbering.com/faq/faq_notes/closures.html.
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.
EXAMPLE 7.9
<html>
<head><title>Closures</title>
<script type="text/javascript">
1
function paint(type, color) {
2
var str = "The " + type + " is " + color; //local variable
3
var tellme = function() { // Anonymous function
document.write("<big>"+str+".</big><br />")
}
4
return tellme ; / return a reference to the function
}
</script>
</head>
<body bgColor="lightgreen">
<h2>Testing a closure</h2>
<script type="text/javascript">
5
var say1 = paint("rose","red") ;/* A reference to the
anonymous is
function is returned */
6
var say2 = paint("sun", "yellow") ;
7
alert(say1); // See the value in say1 Figure 7.13
8
say1() ; // Call the anonymous function
9
say2() ;
</script>
</body>
</html>
 
Search WWH ::




Custom Search