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:
Post a Comment