有没有办法在被调用者中获取调用者函数的名称?

可能重复:
Javascript如何找到调用函数?

今天早上我正在尝试使用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 ,但是这个问题的目标是一个不需要调用者“手动”传递给函数的解决方案。

有没有理由反对做这样的事情?

您曾经能够执行arguments.caller.name ,但在Javascript 1.3中已弃用 。

arguments.callee.caller.name (或只是showMe.caller.name )是另一种方法 。 这是非标准的,但目前在所有主流浏览器中都受支持 。

像这样尝试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); } 

这对你有用吗?

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

注意,这是非标准的javascript。

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/caller

我想这是….

arguments.callee.caller