Is there any way to determine which function called myFunction in javascript?

Go To


Possible Duplicate:
Determine calling function in javascript

Suppose I have a function in javascript, and I want to know who is the caller. Is this possible without using a global variables/parameters approach?

2012-04-04 02:11
by kerzek


To be compatible with a wide selection of browsers, you need something like:

if (typeof arguments.caller == 'function') {
  return arguments.caller;

} else if (typeof arguments.callee == 'function' && 
           typeof arguments.callee.caller == 'function') {
  return arguments.callee.caller;

} else {
  // called from global scope, in strict mode or browser doesn't support
  // either of the above access methods

Note that accessing arguments.callee or caller will throw an exception in ES5 strict mode, the above may avoid that but I can't test it right now.

2012-04-04 02:47
by RobG