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?

Community
  • 1
  • 1
jenswirf
  • 7,087
  • 11
  • 45
  • 65

6 Answers6

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]().

detaylor
  • 7,112
  • 1
  • 27
  • 46
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.

Alexis
  • 4,317
  • 1
  • 25
  • 34
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]();
osahyoun
  • 5,173
  • 2
  • 17
  • 15
1

Try this:

window[callback]();

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

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • +1 For pointing out *never* to use eval! – Rich O'Kelly Feb 09 '12 at 10:42
  • 1
    Not to question your reply, but of many people repeating "eval is evil", only a few can actually explain why. – georg Feb 09 '12 at 10:57
  • @thg435: [here](http://bonsaiden.github.com/JavaScript-Garden/#core.eval) is a short wrap-up: "Any code that makes use of it is to be questioned in its **workings**, **performance** and **security**" – Tomasz Nurkiewicz Feb 09 '12 at 11:01
  • Yeah, this is exactly what I'm talking about. "eval should never be used, because... hmm, well, because it should be avoided". ;) – georg Feb 09 '12 at 11:08
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 + '();');
J. K.
  • 8,268
  • 1
  • 36
  • 35
0

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

Fox32
  • 13,126
  • 9
  • 50
  • 71