How do I trigger a function from a string?

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?


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


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.


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]();
链接地址: http://www.djcxy.com/p/94832.html

上一篇: 如何调用名称在字符串中定义的函数?

下一篇: 如何从字符串触发函数?