Cameron
Cameron

Reputation: 28793

Use string to call function without eval()

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 +")");

Upvotes: 4

Views: 3095

Answers (2)

Alexander
Alexander

Reputation: 12785

You could use a Function constructor .

var func = new Function("console.log('i am a new function')");
func();

Upvotes: 3

Kevin Labécot
Kevin Labécot

Reputation: 1995

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

window[callback]();

Upvotes: 8

Related Questions