PROPERTY:
Function::arguments
[Function.]arguments
The arguments property, which is now deprecated, consists of
an array of all the arguments passed to a function. The arguments
property is only available inside a function, but can be used to refer
to any of the function's arguments by stating the appropriate element
of the array. For example; arguments[0]; newFunction.arguments[1]
etc. (Note that the arguments property can be preceeded by the
function name). The arguments array is especially useful with
functions that can be called with a variable number of arguments, or
with more arguments than they were formally declared to accept.
In this next example, a function is declared to calculate the average
of a variable number of numbers (which are the function's arguments).
By using the arguments array and the arguments.length
property, you can pass the function any number of arguments and have
it return the average of them:
Code:
function calcAverage()
{
var sum = 0
for(var i=0; i<arguments.length; i++)
sum = sum + arguments[i]
var average = sum/arguments.length
return average
}
document.write("Average = " + calcAverage(400, 600, 83))
Output:
Average = 361
The arguments property itself has the following three properties:
PROPERTIES
arguments.callee Property
The arguments.callee property can only be used within the body
of a function and returns a string specifying what that function is.
As the this keyword doesn't refer to the current function, you
can use the arguments.callee property instead.
Syntax: [Function.]arguments.callee
The next example demonstrates the use of this property:
Code:
function testCallee(){return arguments.callee}
document.write(testCallee())
Output:
function testCallee(){return arguments.callee}
arguments.caller Property
The arguments.caller property is deprecated in JavaScript 1.3
and is no longer used, but where it is, it specifies the name of the
function that called the currently executing function.
arguments.length Property
The arguments.length property returns the number of arguments
passed to a function, as opposed to the function.length
property, which returns the number of arguments that a function expects
to receive.
Syntax: [Function.]arguments.length
The distinction between the arguments.length and Function.length
properties is demonstrated in this next example of a function which
is designed to take as its arguments 3 numbers and then calculate the
average of them. If exactly 3 arguments are passed to it, it carries
out the calculation, otherwise it returns an appropriate message:
Code:
function calc3Average(x, y, z)
{
if(arguments.length != calc3Average.length)
return "Use 3 arguments!"
else
var average = (x + y + z)/3
return "The average is " + average
}
|