What mechanism permits a JavaScript function to refer to arguments
from its caller by the name of the calling function and why is it still in the language?
I was looking up tail call optimization (or rather the lack thereof) in V8 and came across this post (https://code.google.com/p/v8/issues/detail?id=457)
Erik Corry's example is given below
function foo(x) {
return bar(x + 1);
}
function bar(x) {
return foo.arguments[0];
}
foo(1)
At first I thought maybe invoking a function sets its arguments
field as some kind of weird global side effect, but it only appears to last for the duration of the call.
function foo(x) {
return bar(x+1);
}
function bar(x) {
return foo.arguments[0];
}
console.log(foo(1)); // prints '1'
console.log(foo.arguments); // prints 'null'
Why is this behavior in the language? Is it useful for anything besides backwards compatibility?
EDIT:
I am not asking about using arguments
to refer to the pseudo-array of arguments in the current function body, e.g.
function variadic() {
for (var i = 0; i < arguments.length; i++) {
console.log("%s-th item is %s", i, JSON.stringify(arguments[i]));
}
}
variadic(1, 2, 3, 4, 5, []);
I am asking about using somefunction.arguments
to refer to arguments
of a caller.
This can be useful if you want to catch errors and compute them inside your own code, so you can clarify things to end user (or just debug) on an integrated output, or send those errors to server so you know there is a problem on your code. All this caller
and arguments
stuff can help on debugging the stack. It can also help on logging (again, debugging stuff), printing the name of the caller function (and possibly its arguments).
Or you can do an esoteric program that uses this information somehow usefully (maybe inside an object function).
The reason why it exists is that this is part of the language (I think why is not a good question here).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With