Call javascript function from a string

0

In my database I have as a string the function to execute and in another field the parameters that are sent to this function, the functions are already declared with their respective return value as I could call them from my string?

That is:

funcionUno=function(val){
  return "Hola 1"+val;
}

funcionDos=function(val){
  return "Hola 2"+val;
}

var EjecutarFuncion="funcionUno";
var enviarParametro="Stack";

I tried:

var result= new Function(EjecutarFuncion)(enviarParametro);
console.log(result);

but I get undefined

    
asked by Rastalovely 18.09.2018 в 23:59
source

3 answers

1

Any function is also a method of the window object.

funcionUno=function(val){
  console.log ("Hola 1 "+val);
}


window["funcionUno"]("Rastalovely");
    
answered by 19.09.2018 / 00:46
source
0

Since my code runs on the server side it is not possible to use window, I solved it in the following way:

funcionUno=function(val){
  return "Hola 1 "+val;
}

funcionDos=function(val){
  return "Hola 2 "+val;
}

var EjecutarFuncion="funcionUno";
var enviarParametro="Stack";

let func = new Function('return ' + EjecutarFuncion)();
var dato=func(enviarParametro);
console.log(dato);
    
answered by 19.09.2018 в 00:58
0

There is a much more comprehensive and complete answer to this question, which was answered by user Jason Bunting at the following link: How to execute a JavaScript function when I have its name as a string

Because this answer is in English, I will translate the content:

Do not use the function eval , unless you are 100% sure you have no other alternative.

As has been mentioned, using something similar would be the best way to do it:

window["functionName"](arguments);

However, this will not work when the function uses namespaces:

window["My.Namespace.functionName"](arguments); // fallará

The following should be executed:

window["My"]["Namespace"]["functionName"](arguments); // funcionará

In order to make it easier and provide flexibility, here is a function to solve this:

function executeFunctionByName(functionName, context /*, args */) {
  var args = Array.prototype.slice.call(arguments, 2);
  var namespaces = functionName.split(".");
  var func = namespaces.pop();
  for(var i = 0; i < namespaces.length; i++) {
    context = context[namespaces[i]];
  }
  return context[func].apply(context, args);
}

With the above code, you can execute the function as follows:

executeFunctionByName("Mi.Namespace.nombreDeFuncion", window, argumentos);

The second parameter is the context in which the function is executed, which can be modified according to your needs:

executeFunctionByName("Namespace.nombreDeFuncion", Mi, argumentos);
    
answered by 19.09.2018 в 01:03