Java Reference
In-Depth Information
every function has a read-only property, named length , which contains the number
of formal parameters of the function. in our case, adder.length will return 2 because the
adder() function declares two formal parameters named x and y .
Tip
A function is an object. The function name is the reference to the function object.
You can assign the function name to another variable and pass it to other functions.
The following snippet of code assigns the reference of the adder() function to a variable
named myAdder and calls the function using the myAdder variable:
// Assigns the reference of the adder function to the variable myAdder
var myAdder = adder;
// Call the function (adder()) referenced by myAdder
var sum = myAdder(5, 10);
print(sum);
15
Working with Function Arguments
Before I discuss how argument passing in functions works, consider the following snippet
of code that calls the adder() function with zero to three arguments:
var sum1 = adder(); // Passes no arguments
var sum2 = adder(10); // Passes only one arguments
var sum3 = adder(10, 5); // Passes two arguments
var sum4 = adder(10, 5, 9); // Passes three arguments - one extra
print("sum1 = " + sum1)
print("sum2 = " + sum2)
print("sum3 = " + sum3)
print("sum4 = " + sum4)
sum1 = NaN
sum2 = NaN
sum3 = 15
sum4 = 15
First thing to notice is that the code executes without any errors, that is, Nashorn
lets you pass arguments to a function that are fewer or greater than the number of formal
parameters of the function. This feature can be good or bad depending on how you think
about it. In a good sense, you can think that all functions in Nashorn are varargs where
 
 
Search WWH ::




Custom Search