AJAX - The Complete Reference

(avery) #1

580 Part IV: Appendixes


return x * 2;
}
result = timesTwo(3);
alert(result);

JavaScript’s parameter passing for functions can be troubling since it is dependent on
the data type passed. Primitive types are passed to functions by value. Composite types are
passed by reference.
Functions have their own local scope. Static scoping is employed. You can nest functions
creating an inner function. For example, in the following code fragment, small1() and
small2() are local to the function big and are only callable from within it.

function big()
{
function small1() { }
function small2() { }

small1();
small2();
}

Invocation with inner functions can get a bit tricky as we have shown throughout the
book. This idea is called a closure. Basically, the states of variables are bound up during the
creation of an inner function so that the function carries around its environment until it
wakes up later on. This is especially useful as we have seen with timers or, more specifically
to this book, when XHRs invoke functions later on when data is made available. As a brief
reminder:

function outer()
{
var x = 10;
function innerFun() { alert(x); };
setTimeout(innerFun,2000);
}
outer();

In this case, the inner function innerFun prints out the variable x, which is local to
outer. However, by the time it wakes up from the timeout two seconds later, the variable x
should be unbound since the function has exited. Given that JavaScript implements this as a
closure, the value is 10. Interestingly, if after the timeout was defined we decided to set x to
20, that would be the bound value later on. If closures confuse you, as they do many
developers, you may want to consult Chapter 3, which has a discussion of them particularly
within the context of Ajax.
Functions are first class data objects in JavaScript, so they can be assigned:

x = window.alert;
x("hi");

They also can be used in-place as literals. For example, here we define a function inline
and pass it to a sort() method for arrays:

sortedArray = myArray.sort(function () { /* do some comparison */});
Free download pdf