HTML and CSS Reference
In-Depth Information
In contrast to what one might expect, the prototype property is not a ref-
erence to the function object's internal prototype (i.e., Function.prototype ).
Rather, it is an object that will serve as the prototype for any object created by using
the function as a constructor. Constructors will be covered in depth in Chapter 7,
Objects and Prototypal Inheritance.
The length property of a function indicates how many formal parameters
it expects, sometimes referred to as the function's arity. Listing 5.4 shows an
example.
Listing 5.4 Function objects length property
TestCase("FunctionTest", {
"test function length property": function () {
assertEquals(2, assert.length);
assertEquals(1, document.getElementById.length);
assertEquals(0, console.log.length); // In Firebug
}
});
The test can be run with JsTestDriver by setting up a project including a con-
figuration file as described in Chapter 3, Tools of the Trade.
The benchmark method in Listing 4.9 in Chapter 4, Test to Learn, used the
length property to determine if the benchmark should be called in a loop. If the
function took no formal parameters, the benchmark function looped it; otherwise
the number of iterations was passed to the function to allow it to loop on its own,
avoiding the overhead of the function calls.
Note in the above example how Firebug's console.log method does not
use formal parameters at all. Still, we can pass as many arguments as we want, and
they are all logged. Chrome's implementation of document.getElementById
also has a length of 0. It turns out that formal parameters is only one of two ways to
access arguments passed to a function.
The Function constructor can be used to create new functions as well. It can
either be called as a function, i.e., Function(p1, p2, ... , pn, body); ,or
used in a new expression, as in new Function(p1, p2, ... , pn, body);
with equal results. Both expressions create a new function object, and accept as
arguments any number of formal parameters the new function should accept along
with an optional function body as a string. Calling the function with no arguments
results in an anonymous function that expects no formal parameters and has no
function body. Listing 5.5 shows an example of defining the assert function via
the Function constructor called as a function.
 
Search WWH ::




Custom Search