JavaScript中arguments、callee与caller详解
本文详细解析JavaScript中arguments、callee和caller三个核心概念。通过Chrome调试器演示,说明arguments是存储实际传递参数的类数组对象;callee指向当前执行的函数;caller保存调用当前函数的外部函数引用。结合具体代码示例,帮助开发者深入理解函数调用机制与上下文关系。
arguments对象详解
arguments为何物?
arguments为函数调用时生成的类数组对象,用于存储实际传入函数的参数,不限于声明的参数列表。
此概念何解?
通过示例代码验证,代码见下。
<!DOCTYPE html>
<head>
<title>arguments</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<script>
function obj(){
//利用instanceof判断arguments
console.log( 'arguments instanceof Array? ' + (arguments instanceof Array) );
console.log( 'arguments instanceof Object? ' + (arguments instanceof Object) );
console.log(arguments);
}
obj();
</script>
</body>
</html>
在Chrome调试器中运行该代码,结果如下图所示。

利用instanceof判断,打印结果显示arguments属于对象类型。
展开打印出的arguments,可见其包含多个属性,其中包含callee。
修改上述代码,调用obj函数时传入参数,但obj函数定义无参数。
具体代码见下。
<!DOCTYPE html>
<head>
<title>arguments</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<script>
function obj(){
console.log( 'arguments instanceof Array? ' + (arguments instanceof Array) );
console.log( 'arguments instanceof Object? ' + (arguments instanceof Object) );
console.log(arguments);
}
//向obj传递参数
obj('monkey','love',24);
</script>
</body>
</html>
通过Chrome调试器,结果如下图所示。

可见arguments包含了传递的三个参数:”monkey”,”love”,24。
因此,arguments存储的是实际传入函数的参数,而非声明的参数。
callee属性解析
callee为何物?
callee是arguments对象的成员,其值为当前正在执行的Function对象。
此含义如何理解?
编写示例demo,观察输出结果即可明了。
代码及结果图见下。
<!DOCTYPE html>
<head>
<title>callee</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<script>
function obj(){
//利用callee
console.log(arguments.callee);
}
obj();
</script>
</body>
</html>
由上图可知,arguments.callee指向包含该arguments对象的函数,此处为obj。

caller属性解析
caller为何物?
caller是函数对象的属性,保存调用当前函数的函数。
注意,特指调用关系,不仅限于闭包。若无父函数,则为null。
同样通过示例demo验证。
代码如下:
<!DOCTYPE html>
<head>
<title>caller</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<script>
//child是parent内的函数,并在parent内执行child
function parent(){
function child(){
//这里child的父函数就是parent
console.log( child.caller );
}
child();
}
//parent1没有被别人调用
function parent1(){
//这里parent1没有父函数
console.log(parent1.caller);
}
//parent2调用了child2
function parent2(){
child2();
}
function child2(){
console.log(child2.caller);
}
/*执行
parent里嵌套了child函数
parent1没有嵌套函数
parent2调用了child2,child2不是嵌套在parent2里的函数
*/
parent();
parent1();
parent2();
</script>
</body>
</html>
打开Chrome调试器,效果图如下。

结合代码与上图理解,是否已掌握caller?
JS大数值转字符串出现科学计数法怎么办
2026-11-05 17:09:21
JS split切割后出现空字符串怎么过滤
2026-11-05 16:00:30
在 React 或 Vue 项目中封装使用 JS 节流防抖
2026-11-05 15:27:29
JavaScript中怎么将带小数的字符串转为整数?
2026-11-05 14:32:38
怎么用JavaScript策略模式重构电商促销计算逻辑?
2026-11-05 14:01:09
