JavaScript 之arguments、caller 和 callee 介紹

1.前言

arguments, caller ,   callee 是什麼?javascript

在javascript 中有什麼樣的做用?本篇會對於此作一些基本介紹。html

2. arguments

arguments:  在函數調用時, 會自動在該函數內部生成一個名爲 arguments的隱藏對象。 該對象相似於數組, 但又不是數組。能夠使用[]操做符獲取函數調用時傳遞的實參。
[html]  view plain  copy
 
  1. <!--by oscar999 2013-1-16-->    
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  3. <html>  
  4. <head>  
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  6. <title>Arguments Test</title>  
  7. </head>  
  8. <body>  
  9. <script>  
  10. function testArg()  
  11. {  
  12.     alert("real parameter count: "+arguments.length);  
  13.     for(var i = 0; i arguments.length; i++)  
  14.     {  
  15.         alert(arguments[i]);  
  16.     }  
  17. }  
  18.   
  19.   
  20. testArg(11);  //count: 1      
  21. testArg('hello','world');  // count: 2    
  22. </script>  
  23. </body>  
  24. </html>  
看上去很簡單。 須要注意的是 argument 保存的實參的信息。

上面有說,   arguments 不是一個數組,何以見得? 執行如下部分就能夠知道了
[javascript]  view plain  copy
 
  1. (function () {  
  2.     alert(arguments instanceof Array); // false  
  3.     alert(typeof(arguments)); // object  
  4. })();  
對於以上當即執行函數寫法不清楚的話, 能夠參考
http://blog.csdn.net/oscar999/article/details/8507919

只有函數被調用時,arguments對象纔會建立,未調用時其值爲null:
[javascript]  view plain  copy
 
  1. alert(new Function().arguments);//return null  

arguments 的完整語法以下:
[function.]arguments[n]
參數function :選項。當前正在執行的 Function 對象的名字。 n :選項。要傳遞給 Function 對象的從0開始的參數值索引。 

3. caller

在一個函數調用另外一個函數時,被調用函數會自動生成一個caller屬性,指向調用它的函數對象。若是該函數當前未被調用,或並不是被其餘函數調用,則caller爲null。

[javascript]  view plain  copy
 
  1. <script>  
  2. function testCaller() {  
  3.     var caller = testCaller.caller;  
  4.     alert(caller);  
  5. }  
  6.   
  7. function aCaller() {  
  8.     testCaller();  
  9. }  
  10.   
  11. aCaller();  

4. callee

當函數被調用時,它的arguments.callee對象就會指向自身,也就是一個對本身的引用。
因爲arguments在函數被調用時纔有效,所以arguments.callee在函數未調用時是不存在的(即null.callee),且解引用它會產生異常。
[javascript]  view plain  copy
 
  1. <script>  
  2. function aCallee(arg) {  
  3.   alert(arguments.callee);  
  4. }  
  5.   
  6. function aCaller(arg1, arg2) {aCallee();}  
  7.   
  8. aCaller();  
  9. </script>  
相關文章
相關標籤/搜索