Function : Object

Every function in JavaScript is actually a Function object.

Browser/User Agent Support

IEMozillaNetscapeOperaSafari
4.0+1.0+3.0+7.0+1.0+

Constructors

ConstructorIEMozillaNetscapeOperaSafari
Creates a new instance of the Function object.
4.0+1.0+3.0+7.0+1.0+
 

Properties

PropertyIEMozillaNetscapeOperaSafari
An array-like object corresponding to the arguments passed to a function.
4.0+1.0+3.0+no1.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+no3.0+nono
 
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

MethodIEMozillaNetscapeOperaSafari
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+nono
 
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

Arguments

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.

Stringarg1, arg2, ... argNNames 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)
StringfunctionBodyA 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 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 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 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

 Object constructor -  only

Specifies the function that creates the Function prototype.

See Also

Object.constructor

Availability

JavaScript 1.1 | JScript 2.0 | ECMAScript v1

Visibility

Number length

Specifies the number of arguments expected by the function.

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

Object prototype

Creates an instance of a Function class.

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

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

FunctionthisArgParameter for the calling object.
FunctionargArrayAn argument array for the 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).

FunctionthisArgParameter for the calling object.
Numberarg1, arg2, ...Arguments for the object. (zero-or-more)

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.

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.

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.

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