# Function : Object
Return to: JavaScript Core index

Every function in JavaScript is actually a Function object.

## Platform Support

IE | Mozilla | Netscape | Opera | Safari
--- | --- | --- | --- | ---
4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+

## Constructors

Constructor | Action | IE | Mozilla | Netscape | Opera | Safari
--- | --- | --- | --- | --- | --- | ---
Function Constructor(String arg1, arg2, ... argN, String functionBody) : Function Creates a new instance of the Function object. | Show Details | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+

### Function(String arg1, arg2, ... argN, String functionBody) : Function

Creates a new instance of the Function object.

Parameters

String | arg1, arg2, ... argN | (zero-or-more)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".
String | functionBody | A string containing the JavaScript statements comprising the function definition.

Returns

Function |

Throws
    Throws a SyntaxError if there was a syntax error in one of the arguments.

## Properties

Property | Action | IE | Mozilla | Netscape | Opera | Safari
--- | --- | --- | --- | --- | --- | ---
invocation arguments : Function An array-like object corresponding to the arguments passed to a function. | Show Details | 4.0+ | 1.0+ | 3.0+ | no | 1.0+

Remarks

  Use the `arguments` object available within functions instead of `Function.arguments`.

See Also

  Arguments

Availability

  JavaScript 1.0|JScript 1.0|ECMAScript v1|deprecated by ECMAScript v3

invocation caller : Function 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. | Show Details | 4.0+ | no | 3.0+ | no | no

  ### Checking the value of a function's `caller` property

  The following code checks the value a function's `caller` property.

      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

constructor : Object Specifies the function that creates the Function prototype. | Show Details | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+

See Also

  Object.constructor

Availability

  JavaScript 1.1|JScript 2.0|ECMAScript v1

length : Number Specifies the number of arguments expected by the function. | Show Details | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+

  ### Using `Function.length` and `arguments.length`

  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:

      addNumbers(3,4,5)   // returns 0
                              addNumbers(3,4)     // returns 7
                              addNumbers(103,104) // returns 207

Remarks

  `length` is external to a function, and indicates how many arguments the function expects, i.e. the number of formal parameters. By contrast, `arguments.length` is local to a function and provides the number of arguments actually passed to the function.

See Also

  Arguments.length

Availability

  JavaScript 1.1|JScript 2.0|ECMAScript v1

prototype : Object Creates an instance of a Function class. | Show Details | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+

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

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 = value`

  where

  `fun`
    The name of the constructor function object you want to change.
  `name`
    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";

  Note that `prototype` is 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

## Functions

Method | Action | IE | Mozilla | Netscape | Opera | Safari
--- | --- | --- | --- | --- | --- | ---
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). | Show Details | 5.5+ | 1.0+ | 4.06+ | 7.0+ | 1.0+

Parameters

Function | thisArg | Parameter for the calling object.
Function | argArray | An argument array for the object.

Returns

Object |

  ### Using `apply` to chain constructors

  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(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 `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.

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

  Function.call

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). | Show Details | 5.5+ | 1.0+ | 4.06+ | 7.0+ | 1.0+

Parameters

Function | thisArg | Parameter for the calling object.
Number | arg1, arg2, ... | (zero-or-more)Arguments for the object.

Returns

Object |

  ### Using `call` to chain constructors for an object

  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");

Remarks

  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.

Throws
    Throws a TypeError if the method is invoked on an object that is not a Function.
See Also

  Function.apply

Availability

  JavaScript 1.5|JScript 5.5|ECMAScript v3

toSource() : String Returns a string representing the source code of the function. | Show Details | 4.0+ | 1.0+ | 3.0+ | no | no

Returns

String |

Remarks

  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

  toString|Object.valueOf

Availability

  JavaScript 1.3|ECMAScript v3

toString() : String Returns a string representing the source code of the function. | Show Details | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+

Returns

String |

Remarks

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

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. | Show Details | 4.0+ | 1.0+ | 3.0+ | 7.0+ | 1.0+

Returns

String |

Remarks

  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

  toString|Object.valueOf

Availability

  JavaScript 1.1|ECMAScript v1

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

Arguments

## Availability

JavaScript 1.0|JScript 1.0|ECMAScript v1

text_javascript aptana_docs