JavaScript 1.2: added | |
Function
constructor:
new Function ([arg1[, arg2[, ... argN]],] functionBody)The
function
statement (see "function" on page 372 for details):
function name([param[, param[, ... param]]]) {
statements
}
Function
objects created with the Function
constructor are evaluated each time they are used. This is less efficient than declaring a function and calling it within your code, because declared functions are compiled.
To return a value, the function must have a return
statement that specifies the value to return.
All parameters are passed to functions by value; the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function. However, if you pass an object as a parameter to a function and the function changes the object's properties, that change is visible outside the function, as shown in the following example:
function myFunc(theObject) {The
theObject.make="Toyota"
}
mycar = {make:"Honda", model:"Accord", year:1998}
x=mycar.make // returns Honda
myFunc(mycar) // pass object mycar to the function
y=mycar.make // returns Toyota (prop was changed by the function)
this
keyword does not refer to the currently executing function, so you must refer to Function
objects by name, even within the function body.
Accessing a function's arguments with the arguments array.
You can refer to a function's arguments within the function by using the arguments
array. See arguments
.
Specifying arguments with the Function constructor.
The following code creates a Function
object that takes two arguments.
var multiply = new Function("x", "y", "return x * y")The arguments
"x"
and "y"
are formal argument names that are used in the function body, "return x * y"
.
The preceding code assigns a function to the variable multiply
. To call the Function
object, you can specify the variable name as if it were a function, as shown in the following examples.
var theAnswer = multiply(7,6)
var myAge = 50Assigning a function to a variable with the Function constructor. Suppose you create the variable
if (myAge >=39) {myAge=multiply (myAge,.5)}
multiply
using the Function
constructor, as shown in the preceding section:
var multiply = new Function("x", "y", "return x * y")This is similar to declaring the following function:
function multiply(x,y) {Assigning a function to a variable using the
return x*y
}
Function
constructor is similar to declaring a function with the function
statement, but they have differences:
var multiply = new Function("...")
, multiply
is a variable for which the current value is a reference to the function created with new Function()
.function multiply() {...}
, multiply
is not a variable, it is the name of a function.function addSquares (a,b) {When a function contains a nested function, you can call the outer function and specify arguments for both the outer and inner function:
function square(x) {
return x*x
}
return square(a) + square(b)
}
a=addSquares(2,3) // returns 13
b=addSquares(3,4) // returns 25
c=addSquares(4,5) // returns 41
function outside(x) {
function inside(y) {
return x+y
}
return inside
}
result=outside(3)(5) // returns 8
// This function returns a string padded with leading zerosThe following statements call the
function padZeros(num, totalLen) {
var numStr = num.toString() // Initialize return value
// as string
var numZeros = totalLen - numStr.length // Calculate no. of zeros
if (numZeros > 0) {
for (var i = 1; i <= numZeros; i++) {
numStr = "0" + numStr
}
}
return numStr
}
padZeros
function.
result=padZeros(42,4) // returns "0042"
result=padZeros(42,2) // returns "42"
result=padZeros(5,4) // returns "0005"
JavaScript 1.2: added | |
arguments
array. This array contains an entry for each argument passed to the function. For example, if a function is passed three arguments, you can refer to the arguments as follows:
arguments[0]The
arguments[1]
arguments[2]
arguments
array can also be preceded by the function name:
myFunc.arguments[0]The
myFunc.arguments[1]
myFunc.arguments[2]
arguments
array is available only within a function body. Attempting to access the arguments
array outside a function declaration results in an error.
You can use the arguments
array if you call a function with more arguments than it is formally declared to accept. This technique is useful for functions that can be passed a variable number of arguments. You can use arguments.length
to determine the number of arguments passed to the function, and then process each argument by using the arguments
array. (To determine the number of arguments declared when a function was defined, use the Function.length
property.)
Each local variable of a function is a property of the arguments
array. For example, if a function myFunc
has a local variable named myLocalVar
, you can refer to the variable as arguments.myLocalVar
.
Each formal argument of a function is a property of the arguments
array. For example, if a function myFunc
has two arguments named arg1
and arg2
, you can refer to the arguments as arguments.arg1
and arguments.arg2
. (You can also refer to them as arguments[0]
and arguments[1]
.)
The arguments
array has the following properties:
Property |
Description
Specifies the function body of the currently executing function. Specifies the name of the function that invoked the currently executing function. (Deprecated)
| |
---|
function myConcat(separator) {You can pass any number of arguments to this function, and it creates a list using each argument as an item in the list.
result="" // initialize list
// iterate through arguments
for (var i=1; i<arguments.length; i++) {
result += arguments[i] + separator
}
return result
}
// returns "red, orange, blue, "
myConcat(", ","red","orange","blue")
// returns "elephant; giraffe; lion; cheetah;"
myConcat("; ","elephant","giraffe","lion", "cheetah")
// returns "sage. basil. oregano. pepper. parsley. "Example 2. This example defines a function that creates HTML lists. The only formal argument for the function is a string that is
myConcat(". ","sage","basil","oregano", "pepper", "parsley")
"U"
if the list is to be unordered (bulleted), or "O"
if the list is to be ordered (numbered). The function is defined as follows:
function list(type) {You can pass any number of arguments to this function, and it displays each argument as an item in the type of list indicated. For example, the following call to the function
document.write("<" + type + "L>") // begin list
// iterate through arguments
for (var i=1; i<arguments.length; i++) {
document.write("<LI>" + arguments[i])
}
document.write("</" + type + "L>") // end list
}
list("U", "One", "Two", "Three")results in this output:
<UL>In server-side JavaScript, you can display the same output by calling the
<LI>One
<LI>Two
<LI>Three
</UL>
write
function instead of using document.write
.
callee
property is available only within the body of a function.
The this
keyword does not refer to the currently executing function. Use the callee
property to refer to a function within the function body.
callee
property.
function myFunc() {The following value is returned:
return arguments.callee
}
function myFunc() { return arguments.callee; }
Function.arguments
caller
property is available only within the body of a function.
If the currently executing function was invoked by the top level of a JavaScript program, the value of caller
is null.
The this
keyword does not refer to the currently executing function, so you must refer to functions and Function
objects by name, even within the function body.
The caller
property is a reference to the calling function, so
functionName.toString
. That is, the decompiled canonical source form of the function.caller
property.
function myFunc() {
if (arguments.caller == null) {
return ("The function was called from the top!")
} else return ("This function's caller was " + arguments.caller)
}
Function.arguments
arguments.length
provides the number of arguments actually passed to a function. By contrast, the Function.length
property indicates how many arguments a function expects.
Function.length
and arguments.length
.
function addNumbers(x,y){If you pass more than two arguments to this function, the function returns 0:
if (arguments.length == addNumbers.length) {
return (x+y)
}
else return 0
}
result=addNumbers(3,4,5) // returns 0
result=addNumbers(3,4) // returns 7
result=addNumbers(103,104) // returns 207
Function.arguments
arity
is external to the function, and indicates how many arguments a function expects. By contrast, arguments.length
provides the number of arguments actually passed to a function.
arity
and arguments.length
.
function addNumbers(x,y){If you pass more than two arguments to this function, the function returns 0:
if (arguments.length == addNumbers.length) {
return (x+y)
}
else return 0
}
result=addNumbers(3,4,5) // returns 0
result=addNumbers(3,4) // returns 7
result=addNumbers(103,104) // returns 207
arguments.length
, Function.length
Object.constructor
.
length
is external to a function, and indicates how many arguments the function expects. By contrast, arguments.length
is local to a function and provides the number of arguments actually passed to the function.
arguments.length
.
arguments.length
prototype
property.fun.prototype.name = valuewhere
fun | The name of the constructor function object you want to change. |
name | |
value |
var array1 = new Array();After you set a property for the prototype, all subsequent objects created with
var array2 = new Array(3);
Array.prototype.description=null;
array1.description="Contains some stuff"
array2.description="Contains other stuff"
Array
will have the property:
anotherArray=new Array()
anotherArray.description="Currently empty"
str_rep
, and uses the statement String.prototype.rep = str_rep
to add the method to all String
objects. All objects created with new String()
then have that method, even objects already created. The example then creates an alternate method and adds that to one of the String
objects using the statement s1.rep = fake_rep
. The str_rep
method of the remaining String
objects is not altered.
var s1 = new String("a")
var s2 = new String("b")
var s3 = new String("c")
// Create a repeat-string-N-times method for all String objects
function str_rep(n) {
var s = "", t = this.toString()
while (--n >= 0) s += t
return s
}
String.prototype.rep = str_rep
s1a=s1.rep(3) // returns "aaa"
s2a=s2.rep(5) // returns "bbbbb"
s3a=s3.rep(2) // returns "cc"
// Create an alternate method and assign it to only one String variable
function fake_rep(n) {
return "repeat " + this + " " + n + " times."
}
s1.rep = fake_repThe function in this example also works on
s1b=s1.rep(1) // returns "repeat a 1 times."
s2b=s2.rep(4) // returns "bbbb"
s3b=s3.rep(6) // returns "cccccc"
String
objects not created with the String
constructor. The following code returns "zzz"
.
"z".rep(3)
toString()
Function
object overrides the toString
method of the Object
object; it does not inherit Object.toString
. For Function
objects, the toString
method returns a string representation of the object.
JavaScript calls the toString
method automatically when a Function
is to be represented as a text value or when a Function
is referred to in a string concatenation.
For Function
objects, the built-in toString
method decompiles the function back into the JavaScript source that defines the function. This string includes the function
keyword, the argument list, curly braces, and function body.
For example, assume you have the following code that defines the Dog
object type and creates theDog,
an object of type Dog
:
function Dog(name,breed,color,sex) {
this.name=name
this.breed=breed
this.color=color
this.sex=sex
}
theDog = new Dog("Gabby","Lab","chocolate","girl")Any time
Dog
is used in a string context, JavaScript automatically calls the toString
function, which returns the following string:
function Dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; }
Object.toString
valueOf()
valueOf
method returns the following values:
function Function() {
[native code]
}
toSource
returns the JavaScript source that defines the object as a string. The method is equivalent to the toString
method of the function.
Function.toString
, Object.valueOf
Last Updated: 11/13/98 10:23:13