Javascript函数调用隐式对象arguments

Js在函数调用时会创建一个隐式的的对象arguments。
arguments包含了函数调用时实际传递给函数的参数数组对象。
App = {};
App.fun0 = function(){
    console.log(arguments)
};


App.fun1 = function(arg1){
    console.log(arguments)
};


App.fun2 = function(arg1, arg2){
    console.log(arguments)
};


App.call1 = function(){
    this.fun0();
    this.fun1(1);
    this.fun2(1,2);
};


App.call2 = function(){
    this.fun1();
    this.fun1(1);
    this.fun1(1,2);
};


App.call1();
App.call2();

输出结果如下:
{}
{ '0': 1 }
{ '0': 1, '1': 2 }
{}
{ '0': 1 }
{ '0': 1, '1': 2 }

可以看到,arguments不管函数声明时的参数个数,而是调用实际传递给函数的参数。
arguments[index]获得参数值;
arguments.length获得实际传递的参数个数;

arguments还有一个callee属性,表示对函数本身的引用,可以用来实现递归调用。
如,计算阶乘:
var sum = function(n){
    if(1==n) {
        return 1;
   } else {
        return n + arguments.callee(n-1);
    }
}
console.log(sum(10));


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值