einstein
einstein

Reputation: 13850

Make a string call a function in JS

I want this to work:

I have defined a function:

function callback_1() {
 // Do something
}

I have a callback string that defines a callback:

var functionString = 'callback_' + 1 + '()';

I want to make that string actually call the function callback_1 How do I do that?

Upvotes: 1

Views: 83

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382132

As your functionString is in fact mainly a function's name, you can do that

window['callback_' + 1]();

This is much secure than eval as it only executes a function you yet have.

If you want to use the functionString you have (with its "()" at the end), you can use

window[functionString.slice(0, -2)]();

Upvotes: 6

Aravindhan
Aravindhan

Reputation: 3626

Try this: it is working for me

        eval(functionString);

Upvotes: 0

Related Questions