AJAX - The Complete Reference

(avery) #1

PART IV


Appendix A: JavaScript Quick Reference 581


It is also possible to define functions using an object style with new and the Function()
constructor.

var myFun = new Function("x","alert('Hi '+x) ");
myFun("Thomas");

Given they are objects like everything else, there are a variety of useful properties you
might explore. For example, you can check how many arguments a function expects by
accessing its length property:

functionName.length

The argument values, in addition to being placed in the declared parameters upon
invocation, are accessible via the functionName.arguments[] array. This array holds the
actual values passed to the function, so it may hold a different number of arguments than
the function expects. With such a feature, you can define variable argument functions that
can work with arbitrary amounts of passed data.

The with Statement


As a convenience for handling object paths, JavaScript supports the with statement.

with ( objectExpression )
statement(s)

The object that objectExpression evaluates to is placed at the front of the scope chain
while statement executes. Statements in statement can therefore utilize methods and
properties of this object without explicitly using the property-accessing operator. An
example of the with statement is shown here:

with (document)
{
write("hello ");
write("world ");
write("last modified on " + lastModified);
}

Some JavaScript pundits quite dislike the with statement, given its ambiguity. For
example, in the last expression if we had a user-defined function called write, would it
invoke that within the with or the standard document.write() method? While we could
certainly look at how the scope chain is consulted, the immediate readability problems of
with is clear even in the simplest of cases.

Exceptions


You can catch programmer-generated and runtime exceptions as shown in Table A-19, but
you cannot catch JavaScript syntax errors, though you may handle them in some browsers
using window.onerror.
Free download pdf