Is there a production safe version of Function.caller in Javascript?
Asked Answered
F

2

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

Faille answered 28/8, 2019 at 5:6 Comment(5)
Check the following answer: https://mcmap.net/q/327994/-how-do-you-find-out-the-caller-function-in-javascript-when-use-strict-is-enabledInstil
Out of curiosity, what are you using it for?Thompson
@Royson the suggested answer error.stack which is non-standardEffloresce
@CodeManiac So do you know any "standard" solution for this? Without having to pass the caller name in a parameter each time?Aero
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).Jere
E
7

One possible way is use Console.trace

function a() {
 b()
}

function b() {
 console.trace()
}

a()

Check the browser console to see output

Effloresce answered 28/8, 2019 at 5:23 Comment(1)
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?...)Aero
A
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).

Aero answered 28/8, 2019 at 7:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.