Core object | |
Implemented in |
Navigator 3.0, LiveWire 1.0 Navigator 4.0: added arity property.
|
Created by
The Function
constructor:
new Function (arg1, arg2, ... argN, functionBody)
Parameters
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, as described in the JavaScript Guide.
| Returns a string representing the specified object. |
Specifying a variable value with a Function object
The following code assigns a function to the variable setBGColor
. This function sets the current document's background color.
var setBGColor = new Function("document.bgColor='antiquewhite'")
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 setBGColor
variable:
var colorChoice="antiquewhite"
You can assign the function to an event handler in either of the following ways:
if (colorChoice=="antiquewhite") {setBGColor()}document.form1.colorButton.onclick=setBGColor
<INPUT NAME="colorButton" TYPE="button"
Creating the variable
VALUE="Change background color"
onClick="setBGColor()">setBGColor
shown above is similar to declaring the following function:
function setBGColor() {
Assigning a function to a variable is similar to declaring a function, but they have differences:
document.bgColor='antiquewhite'
}
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 several ways to call the function multFun
:
var theAnswer = multFun(7,6)
document.write("15*2 = " + multFun(15,2))
<INPUT NAME="operand1" TYPE="text" VALUE="5" SIZE=5>You cannot call the function
<INPUT NAME="operand2" TYPE="text" VALUE="6" SIZE=5>
<INPUT NAME="result" TYPE="text" VALUE="" SIZE=10>
<INPUT NAME="buttonM" TYPE="button" VALUE="Multiply"
onClick="document.form1.result.value=
multFun(document.form1.operand1.value,
document.form1.operand2.value)">
multFun
in an object's event handler property, because event handler properties cannot take arguments. For example, you cannot call the function multFun
by setting a button's onclick
property as follows:
document.form1.button1.onclick=multFun(5,10)
onFocus
event handler (the event handler must be spelled in all lowercase):
window.onfocus = new Function("document.bgColor='antiquewhite'")
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 the Function
constructor for an event handler.
Examples
Example 1. 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'")
Example 2. You can determine whether a function exists by comparing the function name to null. In the following example,
frames[0].onblur = new Function("document.bgColor='lightgrey'")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() Properties
arguments
An array corresponding to the arguments passed to a function.
Property of |
Function
|
Implemented in |
Navigator 3.0, LiveWire 1.0 Navigator 4.0 |
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. In JavaScript 1.2, arguments
includes these additional properties:
arguments
array.
arguments
array.
arguments
properties:
<SCRIPT>
function b(z) {
document.write(arguments.z + "<BR>")
document.write (arguments.caller.x + "<BR>")
return 99
}
function a(x, y) {
return b(534)
}
document.write (a(2,3) + "<BR>")
</SCRIPT>This displays: 534
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.
"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>")
for (var i=1; i<list.arguments.length; i++) {
document.write("<LI>" + list.arguments[i])
document.write("</" + type + "L>")
}
}
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
.
arity
When the LANGUAGE
attribute of the SCRIPT
tag is "JavaScript1.2", this property indicates the number of arguments expected by a function.
Property of |
Function
|
Implemented in | Navigator 4.0, Netscape Server 3.0 |
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
.
<SCRIPT LANGUAGE = "JavaScript1.2">
This script writes:
arity = 2
function addNumbers(x,y){
document.write("length = " + arguments.length + "<BR>")
z = x + y
}
document.write("arity = " + addNumbers.arity + "<BR>")
addNumbers(3,4,5)
</SCRIPT>
length = 3
caller
Returns the name of the function that invoked the currently executing function.
Property of |
Function
|
Implemented in | Navigator 3.0, LiveWire 1.0 |
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
caller
property.
function myFunc() {
if (myFunc.caller == null) {
alert("The function was called from the top!")
} else alert("This function's caller was " + myFunc.caller)
}
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
|
Implemented in | Navigator 3.0, LiveWire 1.0 |
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();
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// Display the results
document.write("<P>s1.rep(3) is " + s1.rep(3)) // "aaa"
document.write("<BR>s2.rep(5) is " + s2.rep(5)) // "bbbbb"
document.write("<BR>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
document.write("<P>s1.rep(1) is " + s1.rep(1)) // "repeat a 1 times."
This example produces the following output:
document.write("<BR>s2.rep(4) is " + s2.rep(4)) // "bbbb"
document.write("<BR>s3.rep(6) is " + s3.rep(6)) // "cccccc"s1.rep(3) is aaa
s2.rep(5) is bbbbb
s3.rep(2) is ccs1.rep(1) is repeat a1 times.
The function in this example also works on
s2.rep(4) is bbbb
s3.rep(6) is ccccccString
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
|
Implemented in | Navigator 3.0, LiveWire 1.0 |
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.
Last Updated: 10/31/97 16:00:33