4

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 +")");
1
  • 1
    Need more context. Where is the function you are trying to call located and what does data.func hold? Commented Oct 17, 2014 at 11:59

2 Answers 2

8

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

window[callback]();
Sign up to request clarification or add additional context in comments.

6 Comments

@epascarello: If it weren't, eval(callback + "()"); wouldn't work, either.
Thanks, what about if I had params? See my updated question. As this doesn't seem to work: window[callback](params);
window[callback].apply(window, params);
Gives me the error Uncaught TypeError: Cannot read property 'apply' of undefined when I try and do that...
In fact window[callback](); doesn't work either... but eval(callback + "()"); does...
|
3

You could use a Function constructor .

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

6 Comments

You might as well eval() it, then.
The op states that he cannot use eval()
What I'm trying to say is that your answer is basically the same as using eval.
well , maybe the op's environment allows use of Function constructor, but not eval() .
And how do I make the callback the name of the function?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.