美文网首页程序员
JavaScript函数的arguments,callee,ca

JavaScript函数的arguments,callee,ca

作者: splinzer | 来源:发表于2018-07-14 13:53 被阅读1次

    arguments只能在函数体内使用,使用场景如下:

    • 你想获取这个函数数量不确定的参数时
    • 你想获取是谁调用了这个函数时


      JavaScript arguments,callee,caller关系示意图

    我们通过以下JavaScript代码执行的结果理解一下:

    function test()
    {
        (function(){
        console.log(arguments.length);
        console.log(arguments[0],arguments[1],arguments[2]);
        console.log(arguments.callee);
        console.log(arguments.callee.caller);
        })(1,2,3)
    }
    test();
    

    在chrome浏览器的console中运行,打印结果见下图:


    arguments相关属性的打印结果

    最后总结一下:

    代码 说明
    arguments arguments是一个对象,作用域仅限函数体内,里面记录了该函数本次被调用相关的信息。
    arguments.length 返回本次调用传给函数的参数数量
    arguments[n] 返回第n+1个参数值
    arguments.callee 返回被调用的函数自身
    arguments.callee.caller 返回函数的调用者(如果不是本例中的匿名函数,可以用函数名调用,形式为fn.caller)

    相关文章

      网友评论

        本文标题:JavaScript函数的arguments,callee,ca

        本文链接:https://www.haomeiwen.com/subject/ypqypftx.html