String with JS Function Name

Asked

Viewed 752 times

4

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

Example:

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

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

I’ve seen it in php if I’m not mistaken.

3 answers

8

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

const f = window[func];

f("parametro");

Take 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");

Behold:

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

const func = "foo";

window[func]("Hello World");

4

I would avoid the use of eval(). You can store your functions in an object (not array, as originally said) of functions and then call passing as key the name of the function you want, like this:

funcoes = {
  soma: function() {

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

  }
}

var funcao = "soma";

funcoes[funcao]();

  • +1 by the idea, but what you did is an object, not an Array.

  • 1

    And for those who voted negative: this idea is as good as the best voted so far. If it were more elaborate it could even be the best answer. It is more organized and works in environments beyond the browser (i.e.: Node.js). Think about it before voting negative.

  • Really is an object, thank you for the correction.

-1

Can be used eval(), although not recommended for safety reasons.

According to the 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);
}

Browser other questions tagged

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