javascript中arguments,callee,caller詳解
arguments是什么?
arguments是函數調用時,創(chuàng)建的一個類似的數組但又不是數組的對象,并且它存儲的是實際傳遞給函數的參數,并不局限于函數聲明的參數列表哦。
尼瑪,什么意思?
寫個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? ' + (arguments instanceof Array) );
console.log( 'arguments instanceof Object? ' + (arguments instanceof Object) );
console.log(arguments);
}
obj();
</script>
</body>
</html>
運行該代碼,通過chrome調試器,可得下圖

我利用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? ' + (arguments instanceof Array) );
console.log( 'arguments instanceof Object? ' + (arguments instanceof Object) );
console.log(arguments);
}
//向obj傳遞參數
obj('monkey','love',24);
</script>
</body>
</html>
通過chrome調試器,可得下圖

大家可以看見,arguments包含了三個我們給它傳遞的參數”monkey”,”love”,24。
所以說,為什么arguments是存儲的實際傳遞給函數的參數呢,而不是函數聲明的參數。
callee是什么?
callee是arguments對象的一個成員,它的值為“正被執(zhí)行的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咯。

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內執(zhí)行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);
}
/*執(zhí)行
parent里嵌套了child函數
parent1沒有嵌套函數
parent2調用了child2,child2不是嵌套在parent2里的函數
*/
parent();
parent1();
parent2();
</script>
</body>
</html>
打開chrome調試器,可得下效果圖

結合代碼和上圖理解,這下理解了caller了么?
相關文章
JavaScript中的document.referrer在各種瀏覽器測試結果
這篇文章主要介紹了JavaScript中的document.referrer在各種瀏覽器測試結果,包括在多種情況下每個瀏覽器能否用document.referrer取到值,非常珍貴的測試結果,需要的朋友可以參考下2014-07-07
簡介JavaScript中getUTCMonth()方法的使用
這篇文章主要介紹了簡介JavaScript中getUTCMonth()方法的使用,是JS入門學習中的基礎知識,需要的朋友可以參考下2015-06-06
javascript instanceof 與typeof使用說明
instanceof和typeof都能用來判斷一個變量是否為空或是什么類型的變量。2010-01-01
javascript學習筆記(五) Array 數組類型介紹
javascript學習筆記之Array 數組類型介紹,需要的朋友可以參考下2012-06-06
基于js 字符串indexof與search方法的區(qū)別(詳解)
下面小編就為大家分享一篇基于js 字符串indexof與search方法的區(qū)別介紹,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12

