How do you find out the caller function in JavaScript when use strict is enabled? How do you find out the caller function in JavaScript when use strict is enabled? javascript javascript

How do you find out the caller function in JavaScript when use strict is enabled?


For what it's worth, I agree with the comments above. For whatever problem you're trying to solve, there are usually better solutions.

However, just for illustrative purposes, here's one (very ugly) solution:

'use strict'function jamie (){    var callerName;    try { throw new Error(); }    catch (e) {         var re = /(\w+)@|at (\w+) \(/g, st = e.stack, m;        re.exec(st), m = re.exec(st);        callerName = m[1] || m[2];    }    console.log(callerName);};function jiminyCricket (){   jamie();}jiminyCricket(); // jiminyCricket

I've only tested this in Chrome, Firefox, and IE11, so your mileage may vary.


Please note that this should not be used in production. This is an ugly solution, which can be helpful for debugging, but if you need something from the caller, pass it as argument or save it into a accessible variable.

The short version of @p.s.w.g answer(without throwing an error, just instantiating one):

    let re = /([^(]+)@|at ([^(]+) \(/g;    let aRegexResult = re.exec(new Error().stack);    sCallerName = aRegexResult[1] || aRegexResult[2];

Full Snippet:

'use strict'function jamie (){    var sCallerName;    {        let re = /([^(]+)@|at ([^(]+) \(/g;        let aRegexResult = re.exec(new Error().stack);        sCallerName = aRegexResult[1] || aRegexResult[2];    }    console.log(sCallerName);};function jiminyCricket(){   jamie();};jiminyCricket(); // jiminyCricket