Why in JavaScript can I refer to arguments in the caller?

What mechanism allows a JavaScript function to refer to arguments to its caller by the name of the calling function, and why is it still in the language?

I was looking for tail call optimization (or rather lack thereof) in V8 and came across this post ( https://code.google.com/p/v8/issues/detail?id=457 )

Eric Corrie'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 that maybe calling the function sets its arguments field as some kind of weird global side effect, but it apparently lasts the entire time the call is made.

 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 language? Is it useful for anything other than backward compatibility?

EDIT:

I am not asking for the use of arguments to reference a pseudo-array of arguments in the current function body, for example

 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 ask for the use of somefunction.arguments to reference the arguments caller.

+5
source share
2 answers

This can be useful if you want to catch errors and compute them inside your own code so that you can clarify the situation to end users (or just debug) on ​​the integrated output or send these errors to the server so that you know that there is a problem with your code . All of these caller and arguments elements can help in debugging the stack. It can also help with registration (again, debugging), printing the name of the calling function (and, possibly, its arguments). Or you can make an esoteric program that somehow uses this information (possibly inside an object function).

The reason why it exists is that it is part of the language (I think why this is not a good question here).

+1
source

You can pass the arguments variable to the called function:

 function foo(x) { return bar(x+1, arguments); } function bar(x, foo_arguments) { return foo(foo_arguments[0]); } 

Or put this variable in a global variable:

 var args = false; function foo(x) { args = arguments; return bar(x+1); } function bar(x) { return foo(args[0]); } 

EDIT:

Or use the caller property for a function:

 function foo(x) { return bar(x+1); } function bar(x) { return foo(bar.caller.arguments[0]); } 

But all this does not really matter to me. Can you clarify what you are trying to accomplish?

-1
source

Source: https://habr.com/ru/post/1237524/


All Articles