2011-04-21 102 views
13

可能重複:
Javascript how do you find the caller function?有沒有辦法在被調用者中獲得調用函數的名稱?

我使用javascript/jQuery的今天早上有點實驗,並試圖捕捉當前執行的函數的調用者的名字。

因此在下面的例子中,日誌會顯示爲runMe作爲調用者,而showMe作爲被調用者。

jQuery(document).ready(function($) { 

    function showMe() { 
    // should log the runMe as the caller and showMe as callee 
    console.log('Callee: ',arguments.callee) 
    console.log('Caller: ',arguments.caller); 
    } 

    function runMe() { 
    // getting executed as a button is pressed. 
    showMe(); 
    } 

    $('a').bind('click', function(e) { 
    e.preventDefault(); 
    runMe(); 
    }); 

}); 

以上顯然不起作用,因此我的問題給大家。

在上面的例子中有一個很好的方法來獲得調用者?

請注意:我知道我能得到的runMe被調用,並將其傳遞到showMe作爲參數,但這個問題的目標是朝着不需要調用者傳遞到函數「手動」的解決方案。

有沒有理由不這樣做?

+0

爲什麼你寫的草書'的jQuery(文檔).ready'但速記'$( 'A')。bind'? – 2011-04-21 23:36:32

+0

至於反對的原因 - 爲什麼你需要這樣做? – Claudiu 2011-04-21 23:39:10

+1

@Claudiu:你會成爲一名優秀的精神病專家。 – 2011-04-21 23:40:50

回答

16

你曾經是能夠做到arguments.caller.name,但這是deprecated in Javascript 1.3

arguments.callee.caller.name(或只是showMe.caller.name)是another way to go。這是所有主流瀏覽器中的non-standard, but currently supported

+1

你爲什麼說它被棄用?棄用的是對象'arguments'的'caller'屬性,雖然在這裏你引用了函數的'caller'屬性,這與你的第二個選項是相同的非標準引用。 – davin 2011-04-21 23:49:32

+0

@達文:你說得對。好點。將編輯。 – 2011-04-21 23:49:56

+0

爲什麼控制檯調用中需要名稱屬性? – 2011-04-22 00:02:40

1

我認爲這是....

arguments.callee.caller

3

嘗試callee.caller這樣

function showMe() { 
     // should log the runMe as the caller and showMe as callee 
     console.log('Callee: ',arguments.callee.name) 
     console.log('Caller: ',arguments.callee.caller.name); 
     } 
相關問題