How can I find the calling function in JavaScript?
A simple way I like to use is arguments.callee.caller.name
.
Say you wanted to know what was calling a function called myFunction:
function myFunction() {
console.log(arguments.callee.caller.name);
/* Other stuff... */
}
The browser support for this isn't that great, though, so you could use arguments.callee.caller.toString() instead. Note that this will give you back the contents of the function that called myFunction, so you will need to dig out the function name from that yourself.
Or, you could use a nice stack trace function like this:
function getStack(){
fnRE = /function\s*([\w\-$]+)?\s*\(/i;
var caller = arguments.callee.caller;
var stack = "Stack = ";
var fn;
while (caller){
fn = fnRE.test(caller.toString()) ? RegExp.$1 || "{?}" : "{?}";
stack += "-->"+fn;
caller = caller.arguments.callee.caller;
};
return stack;
}
Stack Trace via http://www.amirharel.com/2010/01/25/using-caller-and-callee-for-stack-trace/
Like this?
function testOne() {
console.log("Test 1");
logTest();
}
function testTwo() {
console.log("Test 2");
logTest();
}
function logTest() {
console.log("Being called from " + arguments.callee.caller.toString());
}
testOne();
testTwo();
If you use 'use strict';
in your JavaScript file, you need to comment/remove it, because otherwise you'll get something like this:
Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them