How to call a function that prints the name of the calling function?

Asked

Viewed 65 times

2

I have the following function:

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

I want the function imprimir() can print on console.log the information from that function call:

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

Simulating the output of the function criarEvento();

(id: 23, Funcão que chamou: criarEvento)
  • 1

    I don’t understand what you want to print, give an example.

  • @bigown, I want the called function to print the name of the calling function.

  • 1

    The question is because according to this description it doesn’t make sense 'Funcão que chamou: ', nomeFuncao. My initial response interpreted one thing (actually I made the other possible interpretation that seems to be the one you really want).

  • and hit the nail on the head.

2 answers

4

4


Can do that:

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 the arguments because despite being obsolete is accepted in all browsers.

The original question didn’t quite explain what I wanted and even now it still gives room to want something else that I originally answered:

function oNomeDessaFuncao() {}

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

function criarEvento() {
    imprimir(oNomeDessaFuncao);
}

criarEvento();

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.