1.前言
arguments, caller , callee 是什麼?javascript
在javascript 中有什麼樣的做用?本篇會對於此作一些基本介紹。html
2. arguments
arguments: 在函數調用時, 會自動在該函數內部生成一個名爲 arguments的隱藏對象。 該對象相似於數組, 但又不是數組。能夠使用[]操做符獲取函數調用時傳遞的實參。
- <!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 不是一個數組,何以見得? 執行如下部分就能夠知道了
- (function () {
- alert(arguments instanceof Array);
- alert(typeof(arguments));
- })();
對於以上當即執行函數寫法不清楚的話, 能夠參考
http://blog.csdn.net/oscar999/article/details/8507919
只有函數被調用時,arguments對象纔會建立,未調用時其值爲null:
- alert(new Function().arguments);
arguments 的完整語法以下:
[function.]arguments[n]
參數function :選項。當前正在執行的 Function 對象的名字。 n :選項。要傳遞給 Function 對象的從0開始的參數值索引。
3. caller
在一個函數調用另外一個函數時,被調用函數會自動生成一個caller屬性,指向調用它的函數對象。若是該函數當前未被調用,或並不是被其餘函數調用,則caller爲null。
- <script>
- function testCaller() {
- var caller = testCaller.caller;
- alert(caller);
- }
-
- function aCaller() {
- testCaller();
- }
-
- aCaller();
4. callee
當函數被調用時,它的arguments.callee對象就會指向自身,也就是一個對本身的引用。
因爲arguments在函數被調用時纔有效,所以arguments.callee在函數未調用時是不存在的(即null.callee),且解引用它會產生異常。
- <script>
- function aCallee(arg) {
- alert(arguments.callee);
- }
-
- function aCaller(arg1, arg2) {aCallee();}
-
- aCaller();
- </script>