JavaScript函数的arguments,callee,ca
2018-07-14 本文已影响1人
splinzer
arguments只能在函数体内使用,使用场景如下:
- 你想获取这个函数数量不确定的参数时
-
你想获取是谁调用了这个函数时
JavaScript arguments,callee,caller关系示意图
我们通过以下JavaScript代码执行的结果理解一下:
function test()
{
(function(){
console.log(arguments.length);
console.log(arguments[0],arguments[1],arguments[2]);
console.log(arguments.callee);
console.log(arguments.callee.caller);
})(1,2,3)
}
test();
在chrome浏览器的console中运行,打印结果见下图:
![](https://img.haomeiwen.com/i1948206/b09de6b854f41e7e.jpg)
最后总结一下:
代码 | 说明 |
---|---|
arguments | arguments是一个对象,作用域仅限函数体内,里面记录了该函数本次被调用相关的信息。 |
arguments.length | 返回本次调用传给函数的参数数量 |
arguments[n] | 返回第n+1个参数值 |
arguments.callee | 返回被调用的函数自身 |
arguments.callee.caller | 返回函数的调用者(如果不是本例中的匿名函数,可以用函数名调用,形式为fn.caller) |