HTML and CSS Reference
In-Depth Information
return base + num;
};
}
Listing 5.17 uses
adder
to create incrementing and decrementing functions.
Listing 5.17
Incrementing and decrementing functions
TestCase("AdderTest", {
"test should add or subtract one from arg": function () {
var inc = adder(1);
var dec = adder(-1);
assertEquals(3, inc(2));
assertEquals(3, dec(4));
assertEquals(3, inc(dec(3)));
}
});
The scope chain for the
inc
method contains its own activation object at the
front. This object has a
num
property, corresponding to the formal parameter. The
base
variable, however, is not found on this activation object. When JavaScript
does identifier resolution, it climbs the scope chain until it has no more objects.
When
base
is not found, the next object in the scope chain is tried. The next
object is the activation object created for
adder
, where in fact the
base
property
is found. Had the property not been available here, identifier resolution would have
continued on the next object in the scope chain, which in this case is the global
object. If the identifier is not found on the global object, a reference error is thrown.
Inside the functions created and returned from
adder
, the
base
variable is
known as a
free variable
, which may live on after the
adder
function has finished
executing. This behavior is also known as a
closure
, a concept we will dig deeper
into in the next chapter, Chapter 6,
Applied Functions and Closures.
Functions created by the
Function
constructor have different scoping rules.
Regardless of where they are created, these functions only have the global object in
their scope chain, i.e., the containing scope is not added to their scope chain. This
makes the
Function
constructor useful to avoid unintentional closures.
5.3.6 Function Expressions Revisited
With a better understanding of the scope chain we can revisit function expressions
and gain a better understanding of how they work. Function expressions can be use-
ful when we need to conditionally define a function, because function declarations