How to call a function using a dynamic name in JS

canvas, javascript

Solution

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

//variables
var 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 function
this["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);
}

Problem

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 something like that cuz I'm going to call those functions through listening events. Some one knows the right away to do it? Thx. ``` //variables var 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 function for(i=0; i< s.length; i++){ eval(s[i]); } // calling the function this["test"+1]; ```

Original source