有没有办法在被调用者中获取调用者函数的名称? [英] Is there a way to get the name of the caller function within the callee?

查看:93
本文介绍了有没有办法在被调用者中获取调用者函数的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Javascript如何找到来电者功能?

今天早上我正在尝试使用javascript / jQuery,并试图捕获当前正在执行的函数的调用者名称。

I'm experimenting with javascript/jQuery a bit this morning and was trying to capture the caller name of the currently executing function.

所以在下面例如,日志将显示 runMe 作为调用者, showMe 作为被调用者。

So in the below example, the log would show runMe as the caller and showMe as the callee.

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();
  });

});

以上显然不起作用,因此我向大家提问。

The above obviously doesn't work, hence my question to you all.

在上面的例子中是否有一个很好的方式来获得来电者?

Is there a good way to get the caller in the above example?

请注意:我知道我可以得到 runMe 的被叫者并将其作为参数传递给 showMe ,但这个问题的目标是一个不需要调用者手动传递给函数的解决方案。

please note: I am aware I could get the callee of runMe and pass it into showMe as an argument but this question is aiming towards a solution that does not require the caller to be passed into the function 'manually'.

是否有理由拒绝这样做?

Are there reasons against doing something like this?

推荐答案

你曾经能够做 arguments.caller.name ,但这是在Javascript 1.3中弃用

You used to be able to do arguments.caller.name, but this is deprecated in Javascript 1.3.

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

arguments.callee.caller.name (or just showMe.caller.name) is another way to go. This is non-standard, but currently supported in all major browsers.

这篇关于有没有办法在被调用者中获取调用者函数的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆