5

Is there a way to return the function that invoked the current function? Function.caller will only work for non-strict mode applications.

I want to be able to use this functionality for production environment, therefore I need strict mode to be turned on.

Expected return: function itself or the name of function.

function a() {
 b()
}

function b() {
 console.log(b.caller)
}

Function.caller will throw an error when used in strict mode:

Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them

dwen
  • 141
  • 2
  • 7
  • Check the following answer: https://stackoverflow.com/a/29572569/6080889 – dRoyson Aug 28 '19 at 05:28
  • 2
    Out of curiosity, what are you using it for? – Brad Aug 28 '19 at 06:18
  • @Royson the suggested answer [`error.stack`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack) which is non-standard – Code Maniac Aug 28 '19 at 06:42
  • @CodeManiac So do you know any "standard" solution for this? Without having to pass the caller name in a parameter each time? – Bart Hofland Aug 28 '19 at 07:08
  • You should have written "production-safe version", with the hyphen. This is the rule for compound adjectives (words that are combined together to describe another, following word). – GeneC Aug 03 '20 at 21:52

2 Answers2

8

One possible way is use Console.trace

function a() {
 b()
}

function b() {
 console.trace()
}

a()

Check the browser console to see output

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • 2
    And what to do when I want to use the data for other purposes instead of showing it in the console? (Since you say "one possible way", I assume there are other ways as well?...) – Bart Hofland Aug 28 '19 at 07:11
1

There does not seem to be a flexible way of doing that natively in JavaScript.

When using a non-standard solution might be acceptable, you could look into the Error.prototype.stack property. You could use the method in p.s.w.g's answer, as Royson already suggested in a comment.

For a more robust solution for production use, I think you should consider using an external package (like stacktrace.js).

Bart Hofland
  • 3,700
  • 1
  • 13
  • 22