javascript中arguments,callee,caller详解

网络编程 发布日期:2024/10/5 浏览次数:1

正在浏览:javascript中arguments,callee,caller详解

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"" src="/UploadFiles/2021-04-02/201603161150526.png">

我利用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"" src="/UploadFiles/2021-04-02/201603161150537.png">

大家可以看见,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咯。

javascript中arguments,callee,caller详解

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调试器,可得下效果图

javascript中arguments,callee,caller详解

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

几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。