Skip to content Skip to sidebar Skip to footer

How To Call A Function Using A Dynamic Name In Js

I'm trying to call this a function following the same example that I've posted bellow. So the problem is that the method that I'm using to call the function doesn't work... I need

Solution 1:

Usually we should avoid eval. What you are trying to do is possible without using eval too and with a simpler code :

//variablesvar ta = 3213;
var da = 44;
var s = [];

//Create string representation of function
s[1] = function test0(){  alert(" + da + "); };
s[0] = function test1(){  alert(" + ta +"); };

s.forEach((fun) => { this[fun.name] = fun;});// calling the functionthis["test"+1]();

Or simple in your code do :

this["test"+1]();

EDIT:

If you are using string and eval just because you are getting function name as string, instead you can create an object :

var data = {};
for(var i = 0; i<10; i++) {
  data['key'+ i] = function (i) { alert(i); }.bind(null, i);
}

Solution 2:

Another, perhaps cleaner, way to do this:

varTestClass = function() {
    this.test1 = function() {};
    this.test2 = function() {};
    this.test3 = function() {};
...
    this.testN = function() {};
}

var test = newTestClass();

To call the method with name 'test1' you would simply do:

test['test1']();

and so on. This works because properties of objects can be accessed through the array notation.

Solution 3:

Call it in the end with ();

//variablesvar ta = 3213;
var da = 44;
var s = [];

//Create string representation of function
s[1] = "function test0(){  alert(" + da + "); }";
s[0] = "function test1(){  alert(" + ta +"); }";

//"Register" the functionfor(i=0; i< s.length; i++){
	eval(s[i]);
}

// calling the functionthis["test"+1]();

Solution 4:

You can create a function using the Function object.

const data = "test";
const func1 = newFunction("alert("+data+")");
func1(); // alert shows  "test"

You can add arguments

const data = "test";
const func1 = newFunction("arg1","alert(arg1)");
func1("Test argument"); // alert shows "Test argument" 

You can create a named list of functions

const myFunctionList = {};
functioncreateFunction(name,funcBody){
    myFunctionList[name] = newFunction(funcBody);
}
createFunction("test1","alert('test function');");
myFunctionList.test1();  // alert shows 'test function'// or
myFunctionList["test1"]();

Solution 5:

Try This:

let dynamic_func_name = 'alert';
let para_1 = 'Hello';
(newFunction(`${dynamic_func_name}('${para_1}')`))()

Post a Comment for "How To Call A Function Using A Dynamic Name In Js"