JavaScript中arguments、callee与caller详解

作者:代码拾荒时间:2026-10-27 18:49:52浏览:546

本文详细解析JavaScript中arguments、callee和caller三个关键属性的用法与区别。arguments用于获取函数传入的实际参数,callee指向当前执行的函数对象以支持递归,caller则返回调用当前函数的外部函数引用。结合代码示例说明其在参数验证、匿名函数递归及调试中的应用,并简述apply与call的绑定机制。

arguments、callee与caller概述

核心概念:arguments、callee与caller。其中,arguments用于获取传入函数的参数列表;callee指向当前执行的函数主体;caller则指向调用当前函数的外层函数。

该对象封装了当前执行函数及其调用者的参数信息。

caller属性。

返回调用当前函数的函数引用,语法为functionName.caller,其中functionName代表当前执行的函数名。

注意事项:caller属性仅在函数执行期间存在。若由顶层直接调用,其值为null。在字符串语境下,该属性表现同于functionName.toString(),即返回函数的反编译文本。

callee属性。

返回当前正在执行的Function对象,即该函数的具体定义内容。

语法格式:[function.]arguments.callee。

可选参数function,指代当前正在执行的Function对象的名称。

属性说明。

callee的初始值即为当前正在执行的Function对象。

作为arguments对象的成员,callee引用了函数本身,有助于实现匿名函数的递归或保持函数封装性。例如计算1到n的自然数之和。该属性仅在相关函数执行时有效。此外,callee拥有length属性,可用于验证形参与实参长度是否一致:arguments.length表示实参个数,arguments.callee.length表示形参个数。

示例代码:

代码示例与属性验证<script type='text/javascript'>
function test(x,y,z)
{ 
alert("实参长度:"+arguments.length);
alert("形参长度:"+arguments.callee.length);
alert("形参长度:"+test.length);
alert(arguments[ 0 ])
alert(test[ 0 ]) // undefined 没有这种用法
}
//test(1,2,3); 
test(1,2,3,4);
/*
* arguments不是数组(Array类)
*/
Array.prototype.selfvalue = 1 ;
function testAguments() {
 alert( " arguments.selfvalue= " + arguments.selfvalue);
}
alert("Array.sefvalue="+new Array().selfvalue);
testAguments();
/**/ /*
 * 演示函数的caller属性.
 * 说明:(当前函数).caller:返回一个对函数的引用,该函数调用了当前函数
 */
function callerDemo() {
 if (callerDemo.caller) {
 var a = callerDemo.caller.arguments[ 0 ];
 alert(a);
 } else {
 alert( " this is a top function " );
 }
}
function handleCaller() {
 callerDemo();
}
callerDemo();
 handleCaller("参数1","参数2");
/**/ /*
 * 演示函数的callee属性.
 * 说明:arguments.callee:初始值就是正被执行的 Function 对象,用于匿名函数
 */
function calleeDemo() {
 alert(arguments.callee);
}
 calleeDemo();
 (function(arg0,arg1){alert("形数数目为:"+arguments.callee.length)})();
apply与call函数绑定机制/**/ /*
 * 演示apply,call函数的用法
 * 说明:作用都是将函数绑定到另外一个对象上去运行,两者仅在定义参数方式有所区别:
 * apply(thisArg,argArray);
 * call(thisArg[,arg1,arg2…]]);
 * 即所有函数内部的this指针都会被赋值为thisArg
 */
function ObjectA() {
 alert( " 执行ObjectA() " );
 alert(arguments[ 0 ]);
 this .hit = function (msg) {alert(msg)}
 this .info = " 我来自ObjectA "
 }
 function ObjectB() {
 alert( " 执行ObjectB() " );
 // 调用ObjectA()方法,同时ObjectA构造函数中的所有this就会被ObjectB中的this替代
 ObjectA.apply( this ,arguments); // ObjectA.call(this);
 alert( this .info);
 }
 ObjectB('参数0');
var value = " global 变量 " ;
 function Obj() {
 this .value = " 对象! " ;
 }
 function Fun1() {
 alert( this .value);
 }
 Fun1();
 Fun1.apply(window); 
 Fun1.apply(new Obj());
</script>
作者最新文章