JavaScript 1.2: added
JavaScript 1.3: added
JavaScript 1.4: deprecated | |
Function
constructor:
new Function ([arg1[, arg2[, ... argN]],] functionBody)The
function
statement (see "function" on page 237 for details):
function name([param[, param[, ... param]]]) {
statements
}
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:
var multiply = new Function("...")
, multiply
is a variable for which the current value is a reference to the function created with new Function()
.function multiply() {...}
, multiply
is not a variable, it is the name of a 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) {
function inside(y) {
return x+y
}
return inside
}
result=outside(3)(5) // returns 8
arguments
array is also a property of the Function
object and can be preceded by the function name, as follows:
functionName.arguments[i]JavaScript 1.1 and earlier versions. You cannot nest a function statement in another statement or in itself.
// 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"
result=padZeros(42,2) // returns "42"
result=padZeros(5,4) // returns "0005"
apply(thisArg[, argArray])
thisArg | |
argArray |
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.
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");
Function.call
| |
JavaScript 1.2: added
JavaScript 1.3: deprecated
JavaScript 1.4: deprecated | |
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]The
arguments[1]
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)
| |
---|
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]JavaScript 1.1 and 1.2. The following features that were available in JavaScript 1.1 and JavaScript 1.2 have been removed:
myFunc.arguments[1]
myFunc.arguments[2]
arguments
array. For example, if a function myFunc
has a local variable named myLocalVar
, you can refer to the variable as arguments.myLocalVar
.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]
.)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. "
myConcat(". ","sage","basil","oregano", "pepper", "parsley")
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.
callee
property.
function myFunc() {The following value is returned:
return arguments.callee
}
function myFunc() { return arguments.callee; }
Function.arguments
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
functionName.toString
. That is, the decompiled canonical source form of the function.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)
}
Function.arguments
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.
Function.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
Function.arguments
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.
arity
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
arguments.length
, Function.length
call(thisArg[, arg1[, arg2[, ...]]])
thisArg | |
arg1, arg2, ... |
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.
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");
Function.apply
Object.constructor
.
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.
arguments.length
.
arguments.length
prototype
property.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"
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()
toSource
method returns the following values:
function Function() {
[native code]
}
toSource
returns the JavaScript source that defines the object as a string.
Function.toString
, Object.valueOf
toString()
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; }
Object.toString
valueOf()
valueOf
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.
Function.toString
, Object.valueOf
Last Updated: 10/29/98 20:17:12