Home >Web Front-end >JS Tutorial >Introduction to arguments, caller and callee in JavaScript
1. Introduction
What are arguments, caller, callee? What role does
play in javascript? This article will give some basic introduction to this.
2. arguments
arguments: When a function is called, a hidden object named arguments will be automatically generated inside the function. This object is similar to an array, but is not an array. You can use the [] operator to obtain the actual parameters passed when the function is called.
[html]
<script> </p> <p>function testArg() </p> <p>{ </p> <p> alert("real parameter count: "+arguments.length); </p> <p> for(var i = 0; i < arguments.length; i++) </p><p> { </p><p> alert(arguments[i]); } </p><p> </p><p> </p><p>testArg(11); //count: 1 </p><p>testArg('hello','world'); // count: 2 </p><p></script>
Looks very simple. What needs to be noted is the information about the actual parameters saved by argument.
It is said above that arguments is not an array, how can it be seen? You can find out by executing the following part
[javascript]
(function () {
alert(arguments instanceof Array); // false
alert(typeof(arguments)); // object
})() ;
If you are not clear about how to write the above immediate execution function, you can refer to
http://blog.csdn.net/oscar999/article/details/8507919
The arguments object will only be created when the function is called. Its value is null when not called:
[javascript]
alert(new Function().arguments);//return null
arguments The complete syntax is as follows:
[function.]arguments[n]
Parameter function: option. The name of the Function object currently executing. n: option. The 0-based index of the parameter value to be passed to the Function object.
3. caller
When a function calls another function, the called function will automatically generate a caller attribute, pointing to the function object that called it. If the function is not currently called, or is not called by another function, caller is null.
[javascript]
<script> </p> <p>function testCaller() { </p> <p> var caller = testCaller.caller; </p> <p> alert(caller); </p> <p>} </p> <p> </p> <p>function aCaller() { </p> <p> testCaller(); </p> <p>} </p> <p> </p> <p>aCaller(); </p> <p> </p> <p>4. callee</p> <p>When the function is called, its arguments.callee object will point to itself, which is a reference to itself. </p> <p>Since arguments are valid when the function is called, arguments.callee does not exist (i.e. null.callee) when the function is not called, and dereferencing it will generate an exception. </p> <p>[javascript] </p> <p><script> </p> <p>function aCallee(arg) { </p> <p> alert(arguments.callee); </p> <p>} </p> <p> </p> <p>function aCaller(arg1, arg2) {aCallee(); } </p> <p> </p> <p>aCaller(); </p> <p></script>