Calling a function with the variable name

2

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

Follow the functions as an example. The first one is called and takes the name of the program. Call the second one by passing the name, which should call the third case 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...
}
    
asked by anonymous 27.07.2018 / 17:48

2 answers

3

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

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

That is

window["Inicio_" + prg]();

Where prg is the variable that will come as a parameter.

Avoid using eval , not recommended

    
27.07.2018 / 17:54
2

Instead of passing the function name, pass your 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() .
27.07.2018 / 18:01