JS中的arguments

arguments以及caller与arguments.callee

argument

说明:
在JavaScript中,arguments是对象的一个特殊属性。arguments对象就像数组,但是它却不是数组。
属性:
length:获取arguments对象的长度。(函数实参长度)
callee:引用当前正在执行的函数(callee也有length属性,为函数形参长度)

  1. 隐藏参数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    function abc(x,y){
    alert(x+","+y);
      for(var i=0;i<=arguments.length;i+=){
    alert(" "+arguments[i]);
    }
    }
    abc(1,2,3)
    //output:1,2
    //output:1 2 3
  2. 改变参数值

    1
    2
    3
    4
    5
    6
    function abc(x,y,z){
    arguments[2] = "hello";
    for(var i=0;i<=arguments.length;i+=){
    alert(" "+arguments[i]);
    }
    }//output: 1 2 hello
  3. 递归

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    求1到n的自然数之和
    function add(x){
    if(x == 1) return 1;
    else return n + arguments.callee(n-1);
    }
    //其实callee对于匿名函数调用自身时就是一个福音了,比如对于没有命名的函数求1到n自然数之和
    var result = function(x){
    if(x == 1) return 1;
    return x+arguments.callee(x-1);
    }

caller

  1. 说明
    返回一个对函数的引用,该函数调用了当前函数。
    functionName.caller
    functionName 对象是所执行函数的名称。
    如果是顶层对象调用该functionName函数,则caller为null

callee

见上面的递归。