Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Possible Duplicate:
Javascript how do you find the caller function?

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

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?

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?

like image 720
Jannis Avatar asked Apr 21 '11 23:04

Jannis


People also ask

How can I get the caller name?

Navigate to Android Settings –> Accessibility and turn on Who's Calling. You can now activate the app to get the caller's name or number announced in all incoming calls.

How do you find out the caller function in JavaScript?

To find out the caller function, name a non-standard the function. caller property in JavaScript. The Function object is replaced by the name of the function of which you need to find out the parent function name. If the function Welcome was invoked by the top-level code, the value of Welcome.

Why is function caller deprecated?

They are deprecated, because they leak the function caller, are non-standard, hard to optimize and potentially a performance-harmful feature.


2 Answers

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

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

like image 130
Lightness Races in Orbit Avatar answered Oct 18 '22 21:10

Lightness Races in Orbit


Try callee.caller like this

 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);
      }
like image 32
Satyajit Avatar answered Oct 18 '22 21:10

Satyajit