Function
Specifies a string of JavaScript code to be compiled as a function.
JavaScript 1.2: added
JavaScript 1.3: added | |
Created by
TheFunction constructor:
new Function ([arg1[, arg2[, ... argN]],] functionBody)The
function statement (see "function" on page 622 for details):
function name([param[, param[, ... param]]]) {
statements
}
Parameters
Description
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:
-
When you assign a function to a variable using
var multiply = new Function("..."),multiplyis a variable for which the current value is a reference to the function created withnew Function(). -
When you create a function using
function multiply() {...},multiplyis not a variable, it is the name of a function.
- The inner function can be accessed only from statements in the outer function.
- The inner function can use the arguments and variables of the outer function. The outer function cannot use the arguments and variables of the inner 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) {Specifying an event handler with a Function object. The following code assigns a function to a window's
function inside(y) {
return x+y
}
return inside
}
result=outside(3)(5) // returns 8
onFocus event handler (the event handler must be spelled in all lowercase):
window.onfocus = new Function("document.bgColor='antiquewhite'")If a function is assigned to a variable, you can assign the variable to an event handler. The following code assigns a function to the variable
setBGColor.
var setBGColor = new Function("document.bgColor='antiquewhite'")You can use this variable to assign a function to an event handler in either of the following ways:
document.form1.colorButton.onclick=setBGColor
<INPUT NAME="colorButton" TYPE="button"Once you have a reference to a
VALUE="Change background color"
onClick="setBGColor()">
Function object, you can use it like a function and it will convert from an object to a function:
window.onfocus()Event handlers do not take arguments, so you cannot declare any arguments in a
Function constructor for an event handler. For example, you cannot call the function multiply by setting a button's onclick property as follows:
document.form1.button1.onclick=multFun(5,10)
Backward Compatibility
JavaScript 1.1 and earlier versions. You cannot nest a function statement in another statement or in itself.Property Summary
Method Summary
Examples
Example 1. The following function returns a string containing the formatted representation of a number padded with leading zeros.// 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"Example 2. You can determine whether a function exists by comparing the function name to null. In the following example,
result=padZeros(42,2) // returns "42"
result=padZeros(5,4) // returns "0005"
func1 is called if the function noFunc does not exist; otherwise func2 is called. Notice that the window name is needed when referring to the function name noFunc.
if (window.noFunc == null)Example 3. The following example creates
func1()
else func2()
onFocus and onBlur event handlers for a frame. This code exists in the same file that contains the FRAMESET tag. Note that this is the only way to create onFocus and onBlur event handlers for a frame, because you cannot specify the event handlers in the FRAME tag.
frames[0].onfocus = new Function("document.bgColor='antiquewhite'")
frames[0].onblur = new Function("document.bgColor='lightgrey'")
apply
Allows you to apply a method of another object in the context of a different object (the calling object).Syntax
apply(thisArg[, argArray])
Parameters
thisArg | |
argArray |
Description
You can assign a differentthis object when calling an existing function. this refers to the current object, the calling object. With apply, you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.
apply is very similar to call, except for the type of arguments it supports. You can use an arguments array instead of a named set of parameters. With apply, you can use an array literal, for example, apply(this, [name, value]), or an Array object, for example, apply(this, new Array(name, value)).
You can also use arguments for the argArray parameter. arguments is a local variable of a function. It can be used for all unspecified arguments of the called object. Thus, you do not have to know the arguments of the called object when you use the apply method. You can use arguments to pass all the arguments to the called object. The called object is then responsible for handling the arguments.
Examples
You can useapply to chain constructors for an object, similar to Java. In the following example, the constructor for the product object is defined with two parameters, name and value. Another object, prod_dept, initializes its unique variable (dept) and calls the constructor for product in its constructor to initialize the other variables. In this example, the parameter arguments is used for all arguments of the product object's constructor.
function product(name, value){
this.name = name;
if(value > 1000)
this.value = 999;
else
this.value = value;
}
function prod_dept(name, value, dept){
this.dept = dept;
product.apply(product, arguments);
}
prod_dept.prototype = new product();
// since 5 is less than 100 value is set
cheese = new prod_dept("feta", 5, "food");
// since 5000 is above 1000, value will be 999
car = new prod_dept("honda", 5000, "auto");
See also
Function.call
arguments
An array corresponding to the arguments passed to a function.
| |
JavaScript 1.2: added
JavaScript 1.3: deprecated | |
Description
You can refer to a function's arguments within the function by using thearguments 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.)
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)
| |
|---|
Backward Compatibility
JavaScript 1.1 and 1.2. The following features that were available in JavaScript 1.1 and JavaScript 1.2 have been removed:-
Each local variable of a function is a property of the
argumentsarray. For example, if a functionmyFunchas a local variable namedmyLocalVar, you can refer to the variable asarguments.myLocalVar. -
Each formal argument of a function is a property of the
argumentsarray. For example, if a functionmyFunchas two arguments namedarg1andarg2, you can refer to the arguments asarguments.arg1andarguments.arg2. (You can also refer to them asarguments[0]andarguments[1].)
Examples
Example 1. This example defines a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows: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>
<LI>One
<LI>Two
<LI>Three
</UL>
arguments.callee
Specifies the function body of the currently executing function.Description
Thecallee 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.
Examples
The following function returns the value of the function'scallee property.
function myFunc() {The following value is returned:
return arguments.callee
}
function myFunc() { return arguments.callee; }
See also
Function.arguments
arguments.caller
Specifies the name of the function that invoked the currently executing function.Description
caller is no longer used.
The 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
-
If you use it in a string context, you get the result of calling
functionName.toString. That is, the decompiled canonical source form of the function. - You can also call the calling function, if you know what arguments it might want. Thus, a called function can call its caller without knowing the name of the particular caller, provided it knows that all of its callers have the same form and fit, and that they will not call the called function again unconditionally (which would result in infinite recursion).
Examples
The following code checks the value of a function'scaller property.
function myFunc() {
if (arguments.caller == null) {
return ("The function was called from the top!")
} else return ("This function's caller was " + arguments.caller)
}
See also
Function.arguments
arguments.length
Specifies the number of arguments passed to the function.Description
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.
Example
The following example demonstrates the use ofFunction.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
See also
Function.arguments
arity
Specifies the number of arguments expected by the function.Description
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.
Example
The following example demonstrates the use ofarity 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
See also
arguments.length, Function.length
call
Allows you to call (execute) a method of another object in the context of a different object (the calling object).Syntax
call(thisArg[, arg1[, arg2[, ...]]])
Parameters
thisArg | |
arg1, arg2, ... |
Description
You can assign a differentthis object when calling an existing function. this refers to the current object, the calling object.
With call, you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.
Examples
You can usecall to chain constructors for an object, similar to Java. In the following example, the constructor for the product object is defined with two parameters, name and value. Another object, prod_dept, initializes its unique variable (dept) and calls the constructor for product in its constructor to initialize the other variables.
function product(name, value){
this.name = name;
if(value > 1000)
this.value = 999;
else
this.value = value;
}
function prod_dept(name, value, dept){
this.dept = dept;
product.call(this, name, value);
}
prod_dept.prototype = new product();
// since 5 is less than 100 value is set
cheese = new prod_dept("feta", 5, "food");
// since 5000 is above 1000, value will be 999
car = new prod_dept("honda", 5000, "auto");
See also
Function.apply
constructor
Specifies the function that creates an object's prototype. Note that the value of this property is a reference to the function itself, not a string containing the function's name.Description
SeeObject.constructor.
length
Specifies the number of arguments expected by the function.Description
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.
Example
See the example forarguments.length.
See also
arguments.length
prototype
A value from which instances of a particular class are created. Every object that can be created by calling a constructor function has an associatedprototype property.Description
You can add new properties or methods to an existing class by adding them to the prototype associated with the constructor function for that class. The syntax for adding a new property or method is: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"
Example
The following example creates a method,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)
toSource
Returns a string representing the source code of the function.Syntax
toSource()
Parameters
NoneDescription
ThetoSource method returns the following values:
function Function() {
[native code]
}
toSource returns the JavaScript source that defines the object as a string.
See also
Function.toString, Object.valueOf
toString
Returns a string representing the source code of the function.Syntax
toString()
Parameters
None.Description
TheFunction 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; }
See also
Object.toString
valueOf
Returns a string representing the source code of the function.Syntax
valueOf()
Parameters
NoneDescription
ThevalueOf 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.
See also
Function.toString, Object.valueOf
Table of Contents | Previous | Next | Index
Last Updated: 05/28/99 11:59:30
