2011-04-21 104 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); 
     } 
相关问题