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>  
相关文章
相关标签/搜索