Calling a function with the variable name

Asked

Viewed 857 times

2

I have a function that should be called, but its name is mounted dynamically, based on a variable that will come as parameter.

Follow the functions as an example. The first one is called and takes the name of the program. Call the second passing the name, which should call the third if necessary.

// Primeira
function CarregarPrograma(){
   // Códigos.....
   sPrg = $("div#id_prg").attr("data-programa");
   FuncaoEspecifica(sPrg);
}

// Segunda
function FuncaoEspecifica(prg){
   if ($("div#" + prg).attr("data-inicio") == "1"){
      Inicio_ (valor que vier no parãmetro) ;
   }
}

// Terceira que deve ser chamada da segunda.
function Inicio_admcad00002(){
    // Código a ser executado...
}

2 answers

3


Using window["Nome_função"](argumentos), thus:

window["Inicio_" + (valor que vier no parametro)]();

That is to say

window["Inicio_" + prg]();

Where prg is the variable that will come as parameter.

Avoid using eval, is not recommended

  • 1

    I deleted my answer because yours is better.

  • 1

    Thanks Estevao, it worked here!

2

Instead of passing the function name, pass its reference. For example,

const minhaFuncao = () => console.log('minhaFuncao foi executada!');
const chamarQualquerFuncao = (funcaoASerChamada) => funcaoASerChamada();

chamarQualquerFuncao(minhaFuncao); // log: minhaFuncao foi executada!

Some advice:

  • Do not use window to store application data.
  • Do not define function names dynamically.
  • Do not call functions using strings.
  • Do not use eval().

Browser other questions tagged

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