您的位置:首页 > Web前端 > JavaScript

Javascript函数调用隐式对象arguments

2015-05-07 12:09 309 查看
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));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐