Previous     Contents     Index     Next     
Core JavaScript Reference 1.5





Function

xxx I believe that I have removed all client-specific examples from this file.

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.

JavaScript 1.3: added apply, call, and toSource methods; deprecated arguments.caller property.

JavaScript 1.4: deprecated arguments, arguments.callee, arguments.length, and arity properties (arguments remains a variable local to a function rather than a property of Function).  

ECMA version  

ECMA-262  


Created by
The Function constructor:

new Function ([arg1[, arg2[, ... argN]],] functionBody)

The function statement (see function for details):

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


Parameters



arg1, arg2, ... argN

 

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:

  • When you assign a function to a variable using var multiply = new Function("..."), multiply is a variable for which the current value is a reference to the function created with new Function().

  • When you create a function using function multiply() {...}, multiply is not a variable, it is the name of a function.

Nesting functions. You can nest a function within a function. The nested (inner) function is private to its containing (outer) 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.

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

Specifying an event handler with a Function object. The following code assigns a function to a window's 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"
   VALUE="Change background color"
   onClick="setBGColor()">

Once you have a reference to a 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



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

apply

 

Allows you to apply a method of another object in the context of a different object (the calling object).  

call

 

Allows you to call (execute) a method of another object in the context of a different object (the calling object).  

toSource

 

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

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"

Example 2. You can determine whether a function exists by comparing the function name to null. In the following example, 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)
   func1()
else func2()

Example 3. The following example creates 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

This feature is not in the ECMA specification that corresponds to JavaScript 1.3, but is expected in the next version.

Allows you to apply a method of another object in the context of a different object (the calling object).



Method of  

Function  

Implemented in  

JavaScript 1.3  


Syntax
apply(thisArg[, argArray])


Parameters



thisArg

 

Parameter for the calling object  

argArray

 

An argument array for the object  


Description
You can assign a different this 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 use apply 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.



Local variable of  

All function objects  

Property of  

Function (deprecated)  

Implemented in  

JavaScript 1.1, NES 2.0

JavaScript 1.2: added arguments.callee property.

JavaScript 1.3: deprecated arguments.caller property; removed support for argument names and local variable names as properties of the arguments array.

JavaScript 1.4: deprecated arguments, arguments.callee, and arguments.length as properties of Function; retained arguments as a local variable of a function and arguments.callee and arguments.length as properties of this variable.  

ECMA version  

ECMA-262  


Description
The arguments array is a local variable available within all function objects; arguments as a property of Function is no longer used.

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

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.  


Backward Compatibility

JavaScript 1.3 and earlier versions. In addition to being available as a local variable, the arguments array is also a property of the Function object and can be preceded by the function name. For example, if a function myFunc is passed three arguments named arg1, arg2, and arg3, you can refer to the arguments as follows:

myFunc.arguments[0]
myFunc.arguments[1]
myFunc.arguments[2]

JavaScript 1.1 and 1.2. The following features, which were available in JavaScript 1.1 and JavaScript 1.2, have been removed:

  • 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].)


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

JavaScript 1.4: Deprecated callee as a property of Function.arguments, retained it as a property of a function's local arguments variable.  

ECMA version  

ECMA-262  


Description
arguments.callee is a property of the arguments local variable available within all function objects; arguments.callee as a property of Function is no longer used.

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

Deprecated in JavaScript 1.3  


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'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

JavaScript 1.4: Deprecated length as a property of Function.arguments, retained it as a property of a function's local arguments variable.  

ECMA version  

ECMA-262  


Description
arguments.length is a property of the arguments local variable available within all function objects; arguments.length as a property of Function is no longer used.

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

Deprecated in JavaScript 1.4.  


Description
arity is no longer used and has been replaced by the length property.

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


call

This feature is not in the ECMA specification that corresponds to JavaScript 1.3, but is expected in the next version.

Allows you to call (execute) a method of another object in the context of a different object (the calling object).



Method of  

Function  

Implemented in  

JavaScript 1.3  


Syntax
call(thisArg[, arg1[, arg2[, ...]]])


Parameters



thisArg

 

Parameter for the calling object  

arg1, arg2, ...

 

Arguments for the object  


Description
You can assign a different this 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 use call 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.



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)


toSource

This feature is not in the ECMA specification that corresponds to JavaScript 1.3, but is expected in the next version.

Returns a string representing the source code of the function.



Method of  

Function  

Implemented in  

JavaScript 1.3  


Syntax
toSource()


Parameters
None


Description
The toSource method returns the following values:

  • For the built-in Function object, toSource returns the following string indicating that the source code is not available:

       function Function() {
          [native code]
       }

  • For custom functions, toSource returns the JavaScript source that defines the object as a string.

This method is usually called internally by JavaScript and not explicitly in code. You can call toSource while debugging to examine the contents of an object.


See also
Function.toString, Object.valueOf


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:

  • For the built-in Function object, valueOf returns the following string indicating that the source code is not available:

       function Function() {
          [native code]
       }

  • For custom functions, toSource returns the JavaScript source that defines the object as a string. The method is equivalent to the toString method of the function.

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


See also
Function.toString, Object.valueOf


Previous     Contents     Index     Next     
Copyright © 2000 Netscape Communications Corp. All rights reserved.

Last Updated September 28, 2000