↑
Main Page
Closures
function doAdd(iNum) {
alert(iNum + 10);
}
alert(doAdd.toString());
This code outputs the exact text of the
doAdd()
function (see Figure 2-9).
Figure 2-9
Closures
One of the most misunderstood aspects of ECMAScript is its support for
closures.
Closures are functions
whose lexical representation includes variables that aren’t evaluated, meaning that functions are capable
of using variables defined outside of the function itself. Using global variables in ECMAScript is a sim-
ple example of a closure. Consider the following example:
var sMessage = “Hello World!”;
function sayHelloWorld() {
alert(sMessage);
}
sayHelloWorld();
In this code, the variable
sMessage
isn’t evaluated for the function
sayHelloWorld()
while the scripts is
being loaded into memory. The function
captures
sMessage
for later use, which is to say that the interpreter
knows to check the value of
sMessage
when the function is called. When
sayHelloWorld()
is called (on
the last line), the value of
sMessage
is assigned and the message
“Hello World!”
is displayed.
Closures can get more complicated, as when you are defining a function inside of another function, as
shown here:
var iBaseNum = 10;
function addNumbers(iNum1, iNum2) {
function doAddition() {
There are a couple of other methods of the
Function
class that are more relevant to
the discussion of objects and so are described in the next chapter.
65
ECMAScript Basics
05_579088 ch02.qxd 3/28/05 11:35 AM Page 65
Free JavaScript Editor
Ajax Editor
©
→