JavaScript 之arguments、caller 和 callee 介紹

來源:互聯網
上載者:User

1.前言arguments, caller ,   callee 是什嗎?在javascript 中有什麼樣的作用?本篇會對於此做一些基本介紹。 2. argumentsarguments:  在函數調用時, 會自動在該函數內部產生一個名為 arguments的隱藏對象。 該對象類似於數組, 但又不是數組。可以使用[]操作符擷取函數調用時傳遞的實參。[html]  <!--by oscar999 2013-1-16-->    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  <html>  <head>  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  <title>Arguments Test</title>  </head>  <body>  <script>  function testArg()  {      alert("real parameter count: "+arguments.length);      for(var i = 0; i < arguments.length; i++)      {          alert(arguments[i]);      }  }      testArg(11);  //count: 1      testArg('hello','world');  // count: 2    </script>  </body>  </html>  看上去很簡單。 需要注意的是 argument 儲存的實參的資訊。 上面有說,   arguments 不是一個數組,何以見得? 執行以下部分就可以知道了[javascript]  (function () {      alert(arguments instanceof Array); // false      alert(typeof(arguments)); // object  })();  對於以上立即執行函數寫法不清楚的話, 可以參考http://blog.csdn.net/oscar999/article/details/8507919 只有函數被調用時,arguments對象才會建立,未調用時其值為null:[javascript]  alert(new Function().arguments);//return null   arguments 的完整文法如下:[function.]arguments[n]參數function :選項。當前正在執行的 Function 對象的名字。 n :選項。要傳遞給 Function 對象的從0開始的參數值索引。  3. caller在一個函數調用另一個函數時,被調用函數會自動產生一個caller屬性,指向調用它的函數對象。如果該函數當前未被調用,或並非被其他函數調用,則caller為null。 [javascript]  <script>  function testCaller() {      var caller = testCaller.caller;      alert(caller);  }    function aCaller() {      testCaller();  }    aCaller();   4. callee當函數被調用時,它的arguments.callee對象就會指向自身,也就是一個對自己的引用。由於arguments在函數被調用時才有效,因此arguments.callee在函數未調用時是不存在的(即null.callee),且解引用它會產生異常。[javascript]  <script>  function aCallee(arg) {    alert(arguments.callee);  }    function aCaller(arg1, arg2) {aCallee();}    aCaller();  </script>   

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.