How to find out the path followed by a function in js

5
Explaining my scenario, I use emberjs, and it encapsulates every Component within a Controller that will be encapsulated within a Router , and still has a schema of Model , Mixins , Helpers , this when there is no component, or addon, or mixin talking to another component, addon, mixin ( welcome to the modern javascript ) ... Sometimes it gets very difficult to debug the code, know the path of the javascript route, the scope in which such function or method was called, using console.debug(); I can get the current scope of the function, but it is difficult to know where that function was called. Is there any method or way in javascript to find out all the way the function has traveled until it reaches a certain point?

Exemplifying:

function A(){
  B();
}

function B(){
  a.teste();
}

function C(){
  /*Descobrir como o javascript chegou até aqui*/
  console.log("Hellor Weird World!");
  console.debug();
}

var a = {
  teste: function(){
    C();
  }
}

A();
    
asked by anonymous 15.08.2018 / 17:37

1 answer

2

There is a way to find out who called the function, using the local variable arguments . It is worth mentioning that this method only works if you are not using strict mode , ie the file can not contain 'use strict';

Example:

function Hello()
{
    alert("O nome da função que chamou é " + arguments.callee.caller.name);
}

function Main() {
    Hello();
}

Main();

This execution will show on the alert "The name of the function you called is Main" .

However, you need to trace the full path, not just the last caller. In that case we would have to recursively pick up the callers until they are null. The logic would be something like this:

function Hello()
{
    rastrear();
}

function Main() {
    Hello();
}

function Main2() {
    Main();
}

function rastrear() {
    var trace = '';
    var haveTrace = true;

    var caller = arguments.callee.caller;

    trace = caller.name + ' -> ';

    while(haveTrace) {
        if(caller.caller) {
            trace = caller.caller.name + ' -> ' + trace;
            caller = caller.caller;
        } else {
            haveTrace = false;
        }
    }

    console.log(trace);
}

Main2();

This will print to the console the result "Main2 -> Main -> Hello ->" . But attention! Using this function in recursive functions can cause infinite looping!

Another great option would be to use the console.trace(); function. In this case it would look something like this:

function Hello()
{
    console.trace();
}

function Main() {
    Hello();
}

function Main2() {
    Main();
}

Main2();

This will result in something like this on the console:

console.trace
Hello @ VM197:3
Main @ VM197:7
Main2 @ VM197:11

In addition there are other programmable possibilities, but it's already a great starting point.

    
15.08.2018 / 18:12