1

I have a function with a name, like this:

function tony {
   //do something
}

I also have a variable called currentName with the value 'tony', like this:

var currentName = 'tony';

What I want to know is whether there's any way of activating the tony () function by using the variable currentName eg: +currentName+ (); (but I know that doesn't work)?

Any help would be much appreciated. Thank you.

1

2 Answers 2

3

If it's in the global scope, you can use...

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

1 Comment

Wait, this wasn't a yes or no question? ;) +1.
0

This should work:

eval(currentName + '()');

1 Comment

Yeah, I know it should be avoided. Alex's solution is probably also more efficient. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.