How can function A call function B with the same argument list?

K

Khai Doan

I have function A, which need to call function B with the exact same
argument list. What is the correct way to do this?

I had function A:

function A {
B(arguments);
}

but it does not work.

I had function A:

function A {
// code to copy the argument list to another array arr
B(arr);
}

but that does not work neither. In both cases, it tell me that
function B is expecting different number of arguments.

What I am doing wrong?
 
R

RobG

I have function A, which need to call function B with the exact same
argument list. What is the correct way to do this?

I had function A:

function A {
B(arguments);

}

but it does not work.

I had function A:

function A {
// code to copy the argument list to another array arr
B(arr);

}

but that does not work neither. In both cases, it tell me that
function B is expecting different number of arguments.

What I am doing wrong?

You seek the Function's apply method. The first argument is the
object to use for the called function's this keyword (I've used null,
which will result it in being set to the global/window object), the
second is a list object to use for the arguments object (it can be an
Array or other list, such as the arguments object of the calling
function):

function b(){
for (var i=0; i<arguments.length; i++){
alert('arg ' + i + ': ' + arguments);
}
}

function a(){
b.apply(null, arguments);
}

a('fred', 'Sally', 'Jo');

I should probably point you to the ECMAScript Language spec, but I'll
let you find that (it's in the section with the built-in objects).
Here's one for Mozilla.org's Core JavaScript 1.5 Reference:

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

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,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top