首页 > 编程语言 > 详细

Javascript函数调用隐式对象arguments

时间:2015-05-07 12:24:55      阅读:148      评论:0      收藏:0      [点我收藏+]
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));


Javascript函数调用隐式对象arguments

原文:http://blog.csdn.net/xufeng0991/article/details/45559229

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!