javascript中arguments,callee,caller详解

2022-10-18,,,,

arguments是什么?

arguments是函数调用时,创建的一个类似的数组但又不是数组的对象,并且它存储的是实际传递给函数的参数,并不局限于函数声明的参数列表哦。

尼玛,什么意思?

写个demo看看,代码见下

<!doctype html>
  <head>
    <title>arguments</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  </head>
  <body>
    <script>
      function obj(){
        //利用instanceof判断arguments
        console.log( 'arguments instanceof array? ' + (arguments instanceof array) );
        console.log( 'arguments instanceof object? ' + (arguments instanceof object) );
        console.log(arguments);
      }
      obj();
    </script>
  </body>
</html>

运行该代码,通过chrome调试器,可得下图

我利用instanceof判断arguments,从打印的效果看,arguments是一个对象。

然后展开打印出的arguments,可以从上图得知,它里面包括了许多属性,callee也在内。

接下来,我们修改上面的代码,在调用obj函数时,给它传递参数,但obj函数是没有参数的。

具体代码见下

<!doctype html>
  <head>
    <title>arguments</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  </head>
  <body>
    <script>
      function obj(){
        console.log( 'arguments instanceof array? ' + (arguments instanceof array) );
        console.log( 'arguments instanceof object? ' + (arguments instanceof object) );
        console.log(arguments);
      }
      //向obj传递参数
      obj('monkey','love',24);
    </script>
  </body>
</html>

通过chrome调试器,可得下图

大家可以看见,arguments包含了三个我们给它传递的参数”monkey”,”love”,24。

所以说,为什么arguments是存储的实际传递给函数的参数呢,而不是函数声明的参数。

callee是什么?

callee是arguments对象的一个成员,它的值为“正被执行的function对象”。

什么意思呢?

我们写个demo,看看输出结果就知道啦。

代码和结果图见下

<!doctype html>
  <head>
    <title>callee</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  </head>
  <body>
    <script>
      function obj(){
        //利用callee
        console.log(arguments.callee);
      }
      obj();
    </script>
  </body>
</html>

从上面的图片可知,arguments.callee是指向参数arguments对象的函数,在这里就是obj咯。

caller是什么?

caller是函数对象的一个属性,该属性保存着调用当前函数的函数。

注意,是调用。不仅仅包含闭包哦。如果没有父函数,则为null。

还是老样子,我们一直来写个demo看看。

代码如下:

<!doctype html>
  <head>
    <title>caller</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  </head>
  <body>
    <script>
      //child是parent内的函数,并在parent内执行child
      function parent(){
        function child(){
          //这里child的父函数就是parent
          console.log( child.caller );
        }
        child();
      }
      //parent1没有被别人调用
      function parent1(){
        //这里parent1没有父函数
        console.log(parent1.caller);
      }
      //parent2调用了child2
      function parent2(){
        child2();
      }
      function child2(){
        console.log(child2.caller);
      }
      /*执行
       parent里嵌套了child函数
       parent1没有嵌套函数
       parent2调用了child2,child2不是嵌套在parent2里的函数
      */
      parent();
      parent1();
      parent2();
    </script>
  </body>
</html>

打开chrome调试器,可得下效果图

结合代码和上图理解,这下理解了caller了么?

《javascript中arguments,callee,caller详解.doc》

下载本文的Word格式文档,以方便收藏与打印。