[Contents]

Function

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

Core object

Created by

The Function constructor:

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

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 "theForm".

functionBody
A string containing the JavaScript statements comprising the function definition.

Description

Function objects 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.

In addition to defining functions as described here, you can also use the function statement.

Property Summary

arguments
An array corresponding to the arguments passed to a function.

arity
Indicates the number of arguments expected by the function.

caller
Specifies which function called the current function.

prototype
Allows the addition of properties to a Function object.

Method Summary

toString
Returns a string representing the specified object.

Specifying a variable value with a Function object

The following code assigns a function to the variable setColor. This function sets the color panel's color to white.

var setColor = new Function("[[NSColorPanel sharedColorPanel] setColor: [NSColor whiteColor]]")
To call the Function object, you can specify the variable name as if it were a function. The following code executes the function specified by the setColor variable:

var colorChoice="white"
if (colorChoice=="white") {setColor()}
Creating the variable setColor shown above is similar to declaring the following function:

function setColor() {
   [[NSColorPanel sharedColorPanel] setColor: [NSColor whiteColor]]
}
Assigning a function to a variable is similar to declaring a function, but they have differences:

Specifying arguments in a Function object

The following code specifies a Function object that takes two arguments.

var multFun = new Function("x", "y", "return x * y")
The string arguments "x" and "y" are formal argument names that are used in the function body, "return x * y".

The following code shows how to call the function multFun:

var theAnswer = multFun(7,6)
"15*2 = " + multFun(15,2)

Properties

arguments

An array corresponding to the arguments passed to a function.

Property of

Function

Description

You can call a function with more arguments than it is formally declared to accept by using the arguments array. This technique is useful if a function 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 treat each argument by using the arguments array.

The arguments array is available only within a function declaration. Attempting to access the arguments array outside a function declaration results in an error.

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. arguments includes these additional properties:

For example, the following script demonstrates several of the arguments properties:

function b(z) { 
   print(arguments.z)
   print (arguments.caller.x)
   return 99
}
function a(x, y) { 
   return b(534)
}
a(2,3)
This displays:

534
2
99

534 is the actual parameter to b, so it is the value of arguments.z.

2 is a's actual x parameter, so (viewed within b) it is the value of arguments.caller.x.

99 is what a(2,3) returns.

arity

This property indicates the number of arguments expected by a function.

Property of

Function

Description

arity is external to the function, and indicates how many arguments the function expects. By contrast, arguments.length provides the number of arguments actually passed to the function.

Example

The following example demonstrates the use of arity and arguments.length.

function addNumbers(x,y){ 
   print("length = " + arguments.length)
   z = x + y
}
print("arity = " + addNumbers.arity)
addNumbers(3,4,5)
This script writes:

arity = 2
length = 3

caller

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

Property of

Function

Description

The caller property is available only within the body of a function. If used outside a function declaration, the caller property is null.

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 (myFunc.caller == null) {
      print("The function was called from the top!")
   } else print("This function's caller was " + myFunc.caller)
}

See also

Function.arguments

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

Object

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 new 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
// Print the results
print("s1.rep(3) is " + s1.rep(3)) // "aaa"
print("s2.rep(5) is " + s2.rep(5)) // "bbbbb"
print("s3.rep(2) is " + s3.rep(2)) // "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
print("s1.rep(1) is " + s1.rep(1)) // "repeat a 1 times."
print("s2.rep(4) is " + s2.rep(4)) // "bbbb"
print("s3.rep(6) is " + s3.rep(6)) // "cccccc"
This example produces the following output:

s1.rep(3) is aaa
s2.rep(5) is bbbbb
s3.rep(2) is cc
s1.rep(1) is repeat a1 times.
s2.rep(4) is bbbb
s3.rep(6) is 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)

Methods

toString

Returns a string representing the specified object.

Method of

Function

Syntax

toString()

Parameters

None.

Description

Every object has a toString method that is automatically called when it is to be represented as a text value or when an object is referred to in a string concatenation.

You can use toString within your own code to convert an object into a string, and you can create your own function to be called in place of the default toString method.

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; }
For information on defining your own toString method, see the Object.toString method.


[Contents]

Last Updated: 10/31/97 16:00:33


Copyright © 1997 Netscape Communications Corporation