有没有一种方法可以在被调用者中获取调用者函数的名称

Is there a way to get the name of the caller function within the callee?

本文关键字:获取 被调用者 调用者 函数 一种 方法 有没有      更新时间:2023-09-26

可能重复:
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(是另一条路。这是非标准的,在严格模式下不受支持,但目前所有主要浏览器都支持(ref(。

像这个一样尝试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