How do I call a function that prints the name of the calling function?

2

I have the following function:

function imprimir(id, nomeFuncao)
{
  console.log('id: ', id, 'Funcão que chamou: ', nomeFuncao)
}

I want the imprimir() function to print to console.log the information of this function call:

function criarEvento(id, oNomeDessaFuncao)
{
   imprimir(id, oNomeDessaFuncao)
}

Simulating the output of the function criarEvento();

(id: 23, Funcão que chamou: criarEvento)
    
asked by anonymous 02.11.2016 / 01:52

2 answers

4

You can do this:

function imprimir() {
    console.log('Funcão que chamou: ', arguments.callee.caller.name)
}

function criarEvento() {
    imprimir(); //os argumentos são irrelevantes para o problema
}

criarEvento();

I used arguments because although it is obsolete it is accepted in all browsers.

The original question did not explain well what you wanted and even now still gives scope for something else that I originally respond:

function oNomeDessaFuncao() {}

function imprimir(nomeFuncao) {
    console.log('Funcão passada: ', nomeFuncao.toString());
}

function criarEvento() {
    imprimir(oNomeDessaFuncao);
}

criarEvento();
    
02.11.2016 / 02:00
4

It is not a universal or standardized solution, but some browsers accept:

function imprimir(id, nomeFuncao, frase)
{
  console.log( imprimir.caller )
}

See working at CODEPEN .

Note that it returns the entire structure of the function. He would need a parse. It has other methods like arguments.caller , considered obsolete by the documentation, but may be interesting depending on the context.

  

link

    
02.11.2016 / 02:00