myFunction.apply( [ thisScope ], [ args ] ) in ECMAScript 262
Call the function/method, optionally setting a new scope for this
and passing in parameters via an array.
Arguments
name | type | description |
---|---|---|
thisScope | Object |
[optional]
The object to use as thi
|
args | Array | [optional] An array of items to pass as a |
- Return Type
- Object
Description
Like the call()
method, this method of a function object allows you to invoke the function code, while specifying a different scope for it to run in. Unlike that method, parameters to be passed to the called function exist as a single array of parameters, not a comma-separated list.
In addition to the cases where call()
is useful, this method allows you to create an arbitrary number of parameters to pass to the function via code. The following (contrived) example takes input from the user as long as it's not an empty string, and then calls a function which processes the arbitrary number of arguments passed to it.
function EnumerateParams(){
var out='';
for (var i=0,len=arguments.length;i<len;i++){
out+="Parameter #"+i+" is '"+arguments[i]+"'\n";
}
return out;
}
var params = [];
var singleUserResponse;
while ( (singleUserResponse=GetUserInput()) != '' ){
params.push( singleUserResponse );
}
var msg = EnumerateParams.apply(null,params);
The above sample code assumes a function called GetUserInput
, which would be implementation-specific. To help illustrate the how the above would work, consider the following example:
var msg1 = EnumerateParams( 'alpha' , 'beta' , 'gamma' );
var msg2 = EnumerateParams.call( null , 'alpha' , 'beta' , 'gamma' );
var toPass = [ 'alpha' , 'beta' , 'gamma' ];
var msg3 = EnumerateParams.apply( null , toPass );
/***********************************************
msg1, msg2 and msg3 are all the same multiline string:
Parameter #0 is 'alpha'
Parameter #1 is 'beta'
Parameter #2 is 'gamma'
***********************************************/