23 December, 2005

Transmitting arguments from a function to another

Lately, I was wondering how one could call a function from within another function and passing the arguments without knowing them. I point this out because it is very tricky to debug such a thing and Javascript already has the perfect hack to do that!
Try the following :

function test() {
return arguments.length;
}
test(1,2,3);

It returns 3 as espected.
Now try the call from within another function like this :

function test_in() {
test(arguments);
}
test_in(1,2,3);

It returns 1! Surprised ?
As arguments is just a special Array, it is transmitted to the test function as is.
So the test function receives only one argument which length is 3.
I have come up with the solution at the mozilla developer center.
The reserved words 'call' and 'apply' allow you to call a function in a different context than the function context. Using 'call', you give the context and the arguments, but using apply, you give the context and an array of arguments that becomes the arguments object of the called function! And that is just what we wanted.
Doing this :

function test_in() {
test.call(this, arguments);
}
test_in(1,2,3);

It doesn't solve the problem, but doing that :

function test_in() {
test.apply(this, arguments);
}
test_in(1,2,3);

It returns 3 as espected. Here is how javascript itself solves the nested blind call!

No comments: