invoking a function with variable number of arguments

L

laredotornado

Hi,

I'm passing a function, "myFunc" as an argument to another function,
"doFunc". In "doFunc", I am creating an arbitrary number of arguments
to pass to "myFunc". How do I invoke "myFunc" with an arguments array
stored in "argsArr"? Here is the basic function skeleton:

function doFunc(myFunc) {
var argsArr = getArgsArray();
// invoke myFunc with argsArr ... how?
}

Thanks for the help, - Dave
 
V

VK

Hi,

I'm passing a function, "myFunc" as an argument to another function,
"doFunc". In "doFunc", I am creating an arbitrary number of arguments
to pass to "myFunc". How do I invoke "myFunc" with an arguments array
stored in "argsArr"? Here is the basic function skeleton:

function doFunc(myFunc) {
var argsArr = getArgsArray();
// invoke myFunc with argsArr ... how?

}

function doFunc(myFunc) {
myFunc.apply(null,getArgsArray());
}

function getArgsArray() {
return [1,2,3];
}

function f() {
for (var i=0; i<arguments.length; i++) {
window.alert(arguments);
}
}

doFunc(f);
 
R

RobG

Hi,

I'm passing a function, "myFunc" as an argument to another function,
"doFunc". In "doFunc", I am creating an arbitrary number of arguments
to pass to "myFunc". How do I invoke "myFunc" with an arguments array
stored in "argsArr"? Here is the basic function skeleton:

function doFunc(myFunc) {
var argsArr = getArgsArray();
// invoke myFunc with argsArr ... how?

Use Function.prototype.apply:

myFunc.apply(window, argsArr);


<URL: http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Function:apply
 
T

Thomas 'PointedEars' Lahn

RobG said:
Use Function.prototype.apply:

myFunc.apply(window, argsArr);

Needlessly proprietary and error-prone. Should be

myFunc.apply(this, argsArr);

in global context and

myFunc.apply(global, argsArr);

in local context with `global' assigned as

var global = this;

in global context before.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top