Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use string to call function without eval()

Tags:

javascript

I want to pass a string to a function that then will use this string as a callback. e.g.

app.on('notice', function(data) {

    var callback = data.func; // this is a string
    eval(callback + "()"); // trun string into an executable function

});

However I'm using this in an environment which prevents eval() from being used... How can I rewrite this to work without eval?

I've tried:

var self = this; 
return function(){ self[callback]() };

But it doesn't call the function (and I don't get any errors)

Update: I forgot I also need to handle parameters:

e.g.

var params = ['param1', 'param2'];

eval(callback + "("+ params +")");
like image 211
Cameron Avatar asked Dec 20 '22 10:12

Cameron


1 Answers

Use window object. Replace your eval() call with :

window[callback]();
like image 183
Kevin Labécot Avatar answered Jan 04 '23 13:01

Kevin Labécot