arguments对象简介
arguments 是一种类数组对象,它只在函数的内部起作用,并且永远指向当前函数的调用者传入的所有参数,arguments类似Array,但它不是Array。
1.使用arguments来得到函数的实际参数。
arguments[0]代表第一个实参
ep:
function test(a,b,c,d) {
alert(test.length); //4
alert(arguments.length); //2
if(test.length == arguments.length) { //判断形参与实参是否一致
return a+b;
}
}
test(1,2);
2.arguments对象的callee和caller属性
(1).arguments.callee指向函数本身
function test(a,b) {}
arguments.callee 即为 test 函数本身;
arguments.callee.length 即为函数的形参个数 2
(2).arguments.callee.caller 保存着调用当前函数的函数引用(若函数在全局作用域中运行,caller则为 null)
ep:
function add(x,y) {
console.log(arguments.callee.caller);
}
function test(x,y) {
add(x,y);
}
test(1,2); //结果为:function test(x,y) {add(x,y);}
此时,test()在函数内部调用了ad(0函数,所以arguments.callee.caller则指向了test()函数。
3.arguments对象用的最多的,还是递归操作。
ep:
function fact(num) {
if(num < 1)
return 1;
else
// return num*fact(num-1); //(1)
return num*arguments.callee(num-1); //(2)
}
var F = fact;
alert(F(5)); //120
fact = null;
alert(F(5)); //若使用(1)来实现fact()递归,则会报错。fact is not a Function ;若使用(2)来实现递归,则可以输出120