String with function name in JS

4

In javascript , how do I get the value of a string and use a function as a call, I save in the database which function to use in onchange of an input, exe: validaData validaCPF , diaUtil .

Example:

var func = "processaDados";
func("teste",2);

function processaDados(x,y){
    alert(x);
}

I already saw this in php if I'm not mistaken.

    
asked by anonymous 09.10.2017 / 15:01

3 answers

8

The function reference is available in object window through the key equal to the function name. That is, to call the function, just do:

const f = window[func];

f("parametro");

See an example:

function foo(text) {
   console.log(text);
}

const func = "foo";
const f = window[func];

f("Hello World");

Or you can make the call directly:

window[func]("parametro");

See:

function foo(text) {
  console.log(text);
}

const func = "foo";

window[func]("Hello World");
    
09.10.2017 / 15:07
4

I would avoid using eval() . You can save your functions to an object (not an array, as originally said) and then call the function name you want as the key, like this:

funcoes = {
  soma: function() {

    console.log("chamou a função soma");

  }
}

var funcao = "soma";

funcoes[funcao]();
    
09.10.2017 / 15:10
-1

You can use eval() , although not recommended for security reasons.

According to MDN :

  

The eval () method evaluates JavaScript code represented as a string.

With your example:

var func = eval("processaDados");
func("teste",2);
    
function processaDados(x,y){
    console.log(x);
}
    
09.10.2017 / 15:04