Table of Contents | Previous | Next | Index


Function

Specifies a string of JavaScript code to be compiled as a function.

Core object

Implemented in

JavaScript 1.1, NES 2.0

JavaScript 1.2: added arity, arguments.callee properties; added ability to nest functions

ECMA version

ECMA-262

Created by

The Function constructor:

new Function ([arg1[, arg2[, ... argN]],] functionBody)
The function statement (see "function" on page 372 for details):

function name([param[, param[, ... param]]]) {
   statements
}

Parameters

arg1, arg2, ... argN

(Optional) Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier; for example "x" or "theValue".

functionBody

A string containing the JavaScript statements comprising the function definition.

name

The function name.

param

The name of an argument to be passed to the function. A function can have up to 255 arguments.

statements

The statements comprising the body of the function.

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) {
   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)
The 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 = 50
if (myAge >=39) {myAge=multiply (myAge,.5)}
Assigning a function to a variable with the Function constructor. Suppose you create the variable 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) {
   return x*y
}
Assigning a function to a variable using the Function constructor is similar to declaring a function with the function statement, but they have differences:

Nesting functions. You can nest a function within a function. The nested (inner) function is private to its containing (outer) function:

The following example shows nested functions:

function addSquares (a,b) {
   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
When a function contains a nested function, you can call the outer function and specify arguments for both the outer and inner function:

function outside(x) {
   function inside(y) {
      return x+y
   }
   return inside
}
result=outside(3)(5) // returns 8

Backward Compatibility

JavaScript 1.1 and earlier versions. You cannot nest a function statement in another statement or in itself.

Property Summary

Property Description
arguments

An array corresponding to the arguments passed to a function.

arguments.callee

Specifies the function body of the currently executing function.

arguments.caller

Specifies the name of the function that invoked the currently executing function.

arguments.length

Specifies the number of arguments passed to the function.

arity

Specifies the number of arguments expected by the function.

constructor

Specifies the function that creates an object's prototype.

length

Specifies the number of arguments expected by the function.

prototype

Allows the addition of properties to a Function object.

Method Summary

Method Description
toString

Returns a string representing the source code of the function. Overrides the Object.toString method.

valueOf

Returns a string representing the source code of the function. Overrides the Object.valueOf method.

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 zeros
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
}
The following statements call the padZeros function.

result=padZeros(42,4) // returns "0042"
result=padZeros(42,2) // returns "42"
result=padZeros(5,4)  // returns "0005"

arguments

An array corresponding to the arguments passed to a function.

Local variable of

All function objects

Property of

Function

Implemented in

JavaScript 1.1, NES 2.0

JavaScript 1.2: added arguments.callee property

ECMA version

ECMA-262

Description

You can refer to a function's arguments within the function by using the 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]
arguments[1]
arguments[2]
The arguments array can also be preceded by the function name:

myFunc.arguments[0]
myFunc.arguments[1]
myFunc.arguments[2]
The 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

arguments.callee

Specifies the function body of the currently executing function.

arguments.caller

Specifies the name of the function that invoked the currently executing function. (Deprecated)

arguments.length

Specifies the number of arguments passed to the function.

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) {
   result="" // initialize list
   // iterate through arguments
   for (var i=1; i<arguments.length; i++) {
      result += arguments[i] + separator
   }
   return result
}
You can pass any number of arguments to this function, and it creates a list using each argument as an item in the list.

// returns "red, orange, blue, "
myConcat(", ","red","orange","blue")
// returns "elephant; giraffe; lion; cheetah;"
myConcat("; ","elephant","giraffe","lion", "cheetah")
// returns "sage. basil. oregano. pepper. parsley. "
myConcat(". ","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 "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) {
   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
}
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

list("U", "One", "Two", "Three")
results in this output:

<UL>
<LI>One
<LI>Two
<LI>Three
</UL>
In server-side JavaScript, you can display the same output by calling the write function instead of using document.write.


arguments.callee

Specifies the function body of the currently executing function.

Property of

arguments local variable; Function (deprecated)

Implemented in

JavaScript 1.2

ECMA version

ECMA-262

Description

The 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.

Examples

The following function returns the value of the function's callee property.

function myFunc() {
   return arguments.callee
}
The following value is returned:

function myFunc() { return arguments.callee; }

See also

Function.arguments


arguments.caller

Specifies the name of the function that invoked the currently executing function.

Property of

Function

Implemented in

JavaScript 1.1, NES 2.0

Description

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

Examples

The following code checks the value of a function's 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)
}

See also

Function.arguments


arguments.length

Specifies the number of arguments passed to the function.

Property of

arguments local variable; Function (deprecated)

Implemented in

JavaScript 1.1

ECMA version

ECMA-262

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 of Function.length and arguments.length.

function addNumbers(x,y){
   if (arguments.length == addNumbers.length) {
      return (x+y)
   }
   else return 0
}
If you pass more than two arguments to this function, the function returns 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.

Property of

Function

Implemented in

JavaScript 1.2, NES 3.0

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 of arity and arguments.length.

function addNumbers(x,y){
   if (arguments.length == addNumbers.length) {
      return (x+y)
   }
   else return 0
}
If you pass more than two arguments to this function, the function returns 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


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.

Property of

Function

Implemented in

JavaScript 1.1, NES 2.0

ECMA version

ECMA-262

Description

See Object.constructor.


length

Specifies the number of arguments expected by the function.

Property of

Function

Implemented in

JavaScript 1.1

ECMA version

ECMA-262

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 for arguments.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 associated prototype property.

Property of

Function

Implemented in

JavaScript 1.1, NES 2.0

ECMA version

ECMA-262

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 = value
where
fun

The name of the constructor function object you want to change.

name

The name of the property or method to be created.

value

The value initially assigned to the new property or method.

If you add a property to the prototype for an object, then all objects created with that object's constructor function will have that new property, even if the objects existed before you created the new property. For example, assume you have the following statements:

var array1 = new Array();
var array2 = new Array(3);
Array.prototype.description=null;
array1.description="Contains some stuff"
array2.description="Contains other stuff"
After you set a property for the prototype, all subsequent objects created with 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_rep
s1b=s1.rep(1) // returns "repeat a 1 times."
s2b=s2.rep(4) // returns "bbbb"
s3b=s3.rep(6) // returns "cccccc"
The function in this example also works on String objects not created with the String constructor. The following code returns "zzz".

"z".rep(3)

toString

Returns a string representing the source code of the function.

Method of

Function

Implemented in

JavaScript 1.1, NES 2.0

ECMA version

ECMA-262

Syntax

toString()

Parameters

None.

Description

The 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; }

See also

Object.toString


valueOf

Returns a string representing the source code of the function.

Method of

Function

Implemented in

JavaScript 1.1

ECMA version

ECMA-262

Syntax

valueOf()

Parameters

None

Description

The valueOf method returns the following values:

This method is usually called internally by JavaScript and not explicitly in code.

See also

Function.toString, Object.valueOf


Table of Contents | Previous | Next | Index

Last Updated: 11/13/98 10:23:13

Copyright � 1998 Netscape Communications Corporation