Browser/User Agent Support
| IE | Mozilla | Netscape | Opera | Safari | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+ |
|---|
Constructors
| Constructor | IE | Mozilla | Netscape | Opera | Safari |
|---|---|---|---|---|---|
Creates a new instance of the Function object. | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+ |
Properties
| Property | IE | Mozilla | Netscape | Opera | Safari |
|---|---|---|---|---|---|
An array-like object corresponding to the arguments
passed to a function.
| 4.0+ | 1.0+ | 3.0+ | no | 1.0+ |
Specifies the function that invoked the currently
executing function.This property is not part of ECMA-262 Edition 3
standard. It is implemented at least in SpiderMonkey (the JavaScript engine
used in Mozilla) [1] and JScript.
| 4.0+ | no | 3.0+ | no | no |
Specifies the function that creates the Function prototype. | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+ |
Specifies the number of arguments expected by the function. | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+ |
Creates an instance of a Function class. | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+ |
Methods
| Method | IE | Mozilla | Netscape | Opera | Safari |
|---|---|---|---|---|---|
Allows you to apply a method of another object in the
context of a different object (the calling object).
| 5.5+ | 1.0+ | 4.06+ | 7.0+ | 1.0+ |
Allows you to call (execute) a method of another
object in the context of a different object (the calling
object).
| 5.5+ | 1.0+ | 4.06+ | 7.0+ | 1.0+ |
Returns a string representing the source code of the function. | 4.0+ | 1.0+ | 3.0+ | no | no |
Returns a string representing the source code of the
function.
| 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+ |
Returns a string representing the source code of the function. | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+ |
Creating "focus" and "blur" event handlers for a frame
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 scripting is the
only way to create "focus" and "blur" event handlers for
a frame, because you cannot specify the event handlers in
the frame tag.
var frame = frames[0];
frame.onfocus = new Function("document.body.style.backgroundColor = 'white';");
frame.onblur = new Function("document.body.style.backgroundColor = '#bbbbbb';");
Remarks
General
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 parsed only once.
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);
References
Availability
JavaScript 1.0 | JScript 1.0 | ECMAScript v1
Constructor Detail
Function Function(String arg1, arg2, ... argN, String functionBody)
Creates a new instance of the Function object.
| String | 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 or a list of such strings separated with a comma; for example "x", "theValue", or "a,b". (zero-or-more) |
| String | functionBody | A string containing the JavaScript statements comprising the function definition. |
- Throws
- Throws a SyntaxError if there was a syntax error in one of the arguments.
Property Detail
invocation Function arguments
An array-like object corresponding to the arguments passed to a function.
- Remarks
-
Use the
argumentsobject available within functions instead ofFunction.arguments. - See Also
- Availability
JavaScript 1.0 | JScript 1.0 | ECMAScript v1 | deprecated by ECMAScript v3
invocation Function caller
Specifies the function that invoked the currently executing function.This property is not part of ECMA-262 Edition 3 standard. It is implemented at least in SpiderMonkey (the JavaScript engine used in Mozilla) [1] and JScript.
-
Checking the value of a function's
callerpropertyThe following code checks the value a function's
callerproperty.function myFunc() { if (myFunc.caller == null) { return ("The function was called from the top!"); } else return ("This function's caller was " + myFunc.caller); } - Remarks
-
See arguments.caller.
- Availability
JavaScript 1.0, JScript 2.0 | deprecated by ECMAScript
Object constructor - only
Specifies the function that creates the Function prototype.
- See Also
- Availability
JavaScript 1.1 | JScript 2.0 | ECMAScript v1
- Visibility
Number length
Specifies the number of arguments expected by the function.
-
Using
Function.lengthandarguments.lengthThe following example demonstrates the use of
Function.lengthandarguments.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:
addNumbers(3,4,5) // returns 0 addNumbers(3,4) // returns 7 addNumbers(103,104) // returns 207
- Remarks
-
lengthis external to a function, and indicates how many arguments the function expects, i.e. the number of formal parameters. By contrast,arguments.lengthis local to a function and provides the number of arguments actually passed to the function. - See Also
- Availability
JavaScript 1.1 | JScript 2.0 | ECMAScript v1
Object prototype
Creates an instance of a Function class.
-
The following example creates a method,
str_rep, and uses the statementString.prototype.rep = str_repto add the method to allStringobjects. All objects created withnew String()then have that method, even objects already created. The example then creates an alternate method and adds that to one of theStringobjects using the statements1.rep = fake_rep. Thestr_repmethod of the remainingStringobjects 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
Stringobjects not created with theStringconstructor. The following code returns "zzz"."z".rep(3);
- Remarks
-
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 = valuewhere
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
Arraywill have the property:anotherArray=new Array() anotherArray.description="Currently empty";
Note that
prototypeis itself an object, and can be assigned properties and methods via the object literal syntax:function MyFunction() { alert("Created."); } MyFunction.prototype = { alert1: function(str) { alert(str); }, five: 5, alert2: function() { alert("Hi."); } }; var myObject = new MyFunction(); myObject.alert1("There."); myObject.five; myObject.alert2(); - Availability
JavaScript 1.1 | JScript 2.0 | ECMAScript v1
Method Detail
apply(Function thisArg, Function argArray) : Object
Allows you to apply a method of another object in the context of a different object (the calling object).
| Function | thisArg | Parameter for the calling object. |
| Function | argArray | An argument array for the object. |
-
Using
applyto chain constructorsYou can use
applyto chain constructors for an object, similar to Java. In the following example, the constructor for theproductobject is defined with two parameters,nameandvalue. Another object,prod_dept, initializes its unique variable (dept) and calls the constructor forproductin its constructor to initialize the other variables. In this example, the parameterargumentsis 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(this, 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"); - Remarks
-
You can assign a different
thisobject when calling an existing function.thisrefers to the current object, the calling object. Withapply, you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.applyis very similar tocall, except for the type of arguments it supports. You can use an arguments array instead of a named set of parameters. Withapply, you can use an array literal, for example,apply(this, [name, value]), or anArrayobject, for example,apply(this, new Array(name, value)).You can also use
argumentsfor theargArrayparameter.argumentsis 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 theapplymethod. You can useargumentsto pass all the arguments to the called object. The called object is then responsible for handling the arguments. - Throws
- Throws a TypeError if the method is invoked on an object that is not a function, or with a argArray that is not an array or an Arguments object.
- See Also
- Availability
JavaScript 1.2 | JScript 5.5 | ECMAScript v3
call(Function thisArg, Number arg1, arg2, ...) : Object
Allows you to call (execute) a method of another object in the context of a different object (the calling object).
| Function | thisArg | Parameter for the calling object. |
| Number | arg1, arg2, ... | Arguments for the object. (zero-or-more) |
-
Using
callto chain constructors for an objectYou can use
callto chain constructors for an object, similar to Java. In the following example, the constructor for the product object is defined with two parameters,nameandvalue. Another object,prod_dept, initializes its unique variable (dept) and calls the constructor forproductin 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"); - Remarks
-
You can assign a different
thisobject when calling an existing function.thisrefers 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. - Throws
- Throws a TypeError if the method is invoked on an object that is not a Function.
- See Also
- Availability
JavaScript 1.5 | JScript 5.5 | ECMAScript v3
toSource() : String
Returns a string representing the source code of the function.
- Remarks
The
toSourcemethod returns the following values:- For the built-in
Functionobject,toSourcereturns the following string indicating that the source code is not available:
function Function() { [native code] }- For custom functions,
toSourcereturns 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
toSourcewhile debugging to examine the contents of an object.- For the built-in
- See Also
- Availability
JavaScript 1.3 | ECMAScript v3
toString() : String
Returns a string representing the source code of the function.
- Remarks
-
The Function object overrides the toString method of the Object object; it does not inherit
Object.toString. ForFunctionobjects, thetoStringmethod returns a string representation of the object.JavaScript calls the
toStringmethod automatically when aFunctionis to be represented as a text value or when aFunctionis referred to in a string concatenation.For
Functionobjects, the built-intoStringmethod decompiles the function back into the JavaScript source that defines the function. This string includes thefunctionkeyword, the argument list, curly braces, and function body.For example, assume you have the following code that defines the
Dogobject type and createstheDog, an object of typeDog: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
Dogis used in a string context, JavaScript automatically calls thetoStringfunction, which returns the following string:function Dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; } - Throws
- Throws a TypeError if the method is invoked on an object that is not a Function.
- Availability
JavaScript 1.0 | JScript 2.0 | ECMAScript v1
valueOf() : String
Returns a string representing the source code of the function.
- Remarks
The
valueOfmethod returns the following values:- For the built-in
Functionobject,valueOfreturns the following string indicating that the source code is not available:
function Function() { [native code] }- For custom functions,
toSourcereturns the JavaScript source that defines the object as a string. The method is equivalent to thetoStringmethod of the function.
This method is usually called internally by JavaScript and not explicitly in code.
- For the built-in
- See Also
- Availability
JavaScript 1.1 | ECMAScript v1
