contents   index   previous   next



Function apply()

syntax:

function.apply([thisObj[, arguments])

where:

thisObj - object that will be used as the "this" variable while calling this function. If this is not supplied, then the global object is used instead.

 

arguments - array of arguments to pass to the function as an Array object or a list in the form of [arg1, arg2[, ...]]. The brackets "[]" around a list of arguments are required. Note that the similar method Function call() can receive the same arguments as a list. Compare the following ways of passing arguments:

 

   // Uses an Array object

function.apply(this, argArray)

   // Uses brackets

function.apply(this,[arg1,arg2])

   // Uses argument list

function.call(this,arg1,arg2)

return:

variable - the result of calling the function object with the specified "this" variable and arguments.

 

description:

This method is similar to calling the function directly, only the user is able to pass a variable to use as the "this" variable, and the arguments to the function are passed as an array. If arguments is not supplied, then no arguments are passed to the function. If the arguments parameter is not a valid Array object or list of arguments inside of brackets "[]", then a runtime error is generated.

 

see:

Function(), Function call()

 

example:

var myFunction = new Function("a,b","return a + b");

var args = new Array(4,5);

myFunction.apply(global, args);

  //or

myFunction.apply(global, [4,5]);

 

// This code sample will return 9, which is

// the result of calling myFunction with

// the arguments 4 and 5, from the args array.

 


Function call()