美文网首页大话前端让前端飞Web前端之路
关于JS中的arguments、caller 和 callee

关于JS中的arguments、caller 和 callee

作者: fenerchen | 来源:发表于2018-01-19 10:21 被阅读25次

    arguments

    arguments: 在函数调用时, 会自动在该函数内部生成一个名为 arguments的隐藏对象。 该对象类似于数组, 但又不是数组。可以使用[]操作符获取函数调用时传递的实参。

    function testArg()  
    {  
        console.log("real parameter count: "+arguments.length);  
        for(var i = 0; i < arguments.length; i++)  
        {  
            console.log(arguments[i]);  
        }  
    }   
    testArg(11);  //count: 1      
    testArg('hello','world');  // count: 2  
    

    输出

    real parameter count: 1
     11
     real parameter count: 2
     hello
     world
    

    需要注意的是 argument 保存的实参的信息。而且 arguments 不是一个数组。

        (function () {  
            alert(arguments instanceof Array); // false  
            alert(typeof(arguments)); // object  
        })();  
    

    只有函数被调用时,arguments对象才会创建,未调用时其值为null.

        console.log(new Function().arguments);//return null  
    

    caller

    在一个函数调用另一个函数时,被调用函数会自动生成一个caller属性,指向调用它的函数对象。如果该函数当前未被调用,或并非被其他函数调用,则caller为null。

       function testcaller(){
        console.log(testcaller.caller)
       }  
    function tocalltest(){
      testcaller()
    }
    testcaller()//自我运行,未被调用,返回null
    tocalltest()//返回tocalltest
    

    控制台输出

    null
     ƒ tocalltest(){
      testcaller()
    }
    

    callee

    当函数被调用时,它的arguments.callee对象就会指向自身,也就是一个对自己的引用。
    由于arguments在函数被调用时才有效,因此arguments.callee在函数未调用时是不存在的(即null.callee),且解引用它会产生异常。

       function testcallee(arg){
        console.log(arguments.callee); 
       }  
    function tocalltest(arg){
      testcallee(arg);
    }
    
    tocalltest()
    

    控制台输出

    ƒ testcallee(arg){
        console.log(arguments.callee); 
       }
    

    参考资料http://blog.csdn.net/oscar999/article/details/8511335

    相关文章

      网友评论

        本文标题:关于JS中的arguments、caller 和 callee

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