Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Is there a way to use a string as a callback without eval()?

So I need to make make a callback in one of my functions, but due to the way the whole program is working, I need to pass the callback function name in the form of a string rather than the function itself.

For example:

function doThings(callback){
    alert('hello');
    eval(callback + '();');
}

function test(){
    alert('world!');
}

var func = 'test';

doThings(func);

In short, I'm trying to dynamically change which function is used, and I have to use a string to represent the callback function rather than an actual function reference.

I keep reading eval is evil - is there any way to do this without eval()?

EDIT: I do not have the ability to list out the functions in an object beforehand. I also need to pass an array as individual arguments to this function, and for some reason .apply() doesn't get along well with window[callback]()

like image 204
geekman Avatar asked Nov 02 '16 10:11

geekman


2 Answers

You can do this, in this way.

function doThings(callback){
    alert('hello');
    window[callback]();
}

function test(){
    alert('world!');
}

var func = 'test';

doThings(func);

Or you can pass the full function in string and use the Function constructor.

function doThings(callback){
    alert('hello');
    (new Function('return '+callback)())();
}

function test(){
    alert('world!');
}

var func = test.toString();

doThings(func);
like image 177
Steeve Pitis Avatar answered Oct 18 '22 15:10

Steeve Pitis


Store the functions in an object. Use the property names to access them.

function doThings(callback) {
  alert('hello');
  my_possible_functions[callback]();
}

function test() {
  alert('world!');
}

var my_possible_functions = {};
my_possible_functions.test = test;


var func = 'test';
doThings(func);
like image 28
Quentin Avatar answered Oct 18 '22 15:10

Quentin