HTML and CSS Reference
In-Depth Information
Listing 5.5 Creating a function via Function
var assert = Function("message", "expr",
"if (!expr) { throw new Error(message); }" +
"assert.count++; return true;");
assert.count = 0;
When creating functions this way, we can provide the formal parameters in a
number of ways. The most straightforward way is to pass one string per parameter,
as in the above example. However, we can also pass a single comma-separated string,
or a mix of the two, i.e., Function("p1,p2,p3", "p4", body); .
The Function constructor is useful when the function body needs to be
dynamically compiled, such as when creating functions tailored to the running
environment or a set of input values, which can result in highly performant code.
5.2 Calling Functions
JavaScript offers two ways of calling a function—directly using parentheses or
indirectly using the call and apply methods inherited from Function.
prototype . Direct invocation works as one would expect, as seen in Listing 5.6.
Listing 5.6 Calling a function directly
assert("Should be true", typeof assert == "function");
When calling a function, JavaScript performs no check on the number of ar-
guments. You can pass zero, one, or ten arguments to a function regardless of the
number of formal parameters it specifies. Any formal parameter that does not receive
an actual value will have undefined as its value.
5.2.1 The arguments Object
All of a function's arguments are available through the array-like object argu-
ments . This object has a length property, denoting the number of received
arguments, and numeric indexes from 0 to length - 1 corresponding to the ar-
guments passed when calling the function. Listing 5.7 shows the assert function
using this object rather than its formal parameters.
 
 
Search WWH ::




Custom Search