0

I implemented a small (and probably not standard) function to get the call stack in JavaScript. However, this piece of code below only gets the function references. Is it possible the object to every caller?

function getCallStack() {
  let stack = [];
  let caller = arguments.callee.caller;

  while (caller !== null) {
   stack.push(caller); // I would like "stack.push([caller, getObject(caller)]);
   caller = caller.caller; 
  }
  return stack;
}

If I execute the following piece of code console.log(getCallStack()), I can get something like [ [Function: f3], [Function: f2], [Function: f1] ]. I would like to get something like [ [[Function: f3], obj3], [[Function: f2], obj2], [[Function: f1], obj1] ] where obj1, obj2, obj3 are JUST references to the objects.

Naive Developer
  • 700
  • 1
  • 9
  • 17
  • References to *what* objects? – Pointy Jan 02 '20 at 14:45
  • I believe this will help you: https://stackoverflow.com/questions/591857/how-can-i-get-a-javascript-stack-trace-when-i-throw-an-exception – ROOT Jan 02 '20 at 14:47
  • @Pointy, object of each caller, eg. `obj1.f1();`, I want `obj1` – Naive Developer Jan 02 '20 at 14:57
  • You can't access that, I don't think. What you're asking for is how `this` is bound in each parent function, and that's not exposed. If you check that answer linked in another comment you'll see that there are more modern ways of getting stack traces. – Pointy Jan 02 '20 at 15:00
  • @mamounothman , console.trace only returns these values as a string, but I require their references. – Naive Developer Jan 02 '20 at 15:02
  • @Pointy thanks, but I require to analyze the trace to make some decisions, for example, execute some function if the trace contains the `obj1` executing the method `f1`. – Naive Developer Jan 02 '20 at 15:06
  • What I'm saying is that JavaScript, via `arguments` or anything else, does not provide access to that information. Things like the debugger and `console.trace()` can "cheat" because they have access to the runtime via non-JavaScript APIs. – Pointy Jan 02 '20 at 15:09
  • @NaiveDeveloper there are other technique in that issue that can be used to trace back the whole stack, e.g answer by user2223787 or maybe you will need a whole framework around your codebase to trace everything, e.g https://www.stacktracejs.com/ – ROOT Jan 02 '20 at 15:19

0 Answers0