0

Possible Duplicate:
How to execute a JavaScript function when I have its name as a string

I have this function

function myfunc() {
  alert('it worked!');
}

and this variable which is a string

var callback = 'myfunc';

How do I trigger the function from that string?

2

6 Answers 6

2

Assuming that the function is declared globally it will be contained in the window object so you can call it using window[callback]().

Globally declared functions are stored in the window object so you would be able to reference myfunc using window.myfunc. As with other properties on JavaScript objects you can use the brace syntax instead of the dot notation which would be window["myfunc"] since you have the string "myfunc" contained in your callback variable you can simply use that instead. Once you have the reference you call it as a function which gives window[callback]().

Sign up to request clarification or add additional context in comments.

1 Comment

But shouldn't it be window instead of Window?
2

If you're doing this in browser, try this: window[callback]()

It is also possible to use eval — something like eval(callback + '()') — but this is very inefficient and not recommended.

Also, you may want to consider assigning the function itself instead of its name to the callback variable:

function myfunc() {...}
var callback = myfunc
...
callback()  # trigger callback

This would work in many cases, but of course, sometimes you just need to pass it as a string.

Comments

1

If this is code running on the browser, then myfun is a method of the window object. You can invoke the method like so:

window[callback]();

Comments

1

Try this:

window[callback]();

And don't be tempted to use eval(), never, ever!

4 Comments

+1 For pointing out never to use eval!
Not to question your reply, but of many people repeating "eval is evil", only a few can actually explain why.
@thg435: here is a short wrap-up: "Any code that makes use of it is to be questioned in its workings, performance and security"
Yeah, this is exactly what I'm talking about. "eval should never be used, because... hmm, well, because it should be avoided". ;)
1

If it's a global function, you can call is as

window[callback]();

If not, you will probably have to evaluate it.

eval(callback + '();');

Comments

0

You should pass the function instead of a string with the name. Then you cann call it via callback()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.