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
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
Share Improve this question asked Aug 28, 2019 at 5:06 dwendwen 1412 silver badges7 bronze badges 5- Check the following answer: stackoverflow./a/29572569/6080889 – dRoyson Commented Aug 28, 2019 at 5:28
- 2 Out of curiosity, what are you using it for? – Brad Commented Aug 28, 2019 at 6:18
-
@Royson the suggested answer
error.stack
which is non-standard – Code Maniac Commented Aug 28, 2019 at 6: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 Commented Aug 28, 2019 at 7:08
- You should have written "production-safe version", with the hyphen. This is the rule for pound adjectives (words that are bined together to describe another, following word). – GeneC Commented Aug 3, 2020 at 21:52
2 Answers
Reset to default 7One possible way is use Console.trace
function a() {
b()
}
function b() {
console.trace()
}
a()
Check the browser console to see output
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 ment.
For a more robust solution for production use, I think you should consider using an external package (like stacktrace.js).