I have a JavaScript variable which contains the name of a JavaScript function. This function exists on the page by having been loaded in and placed using $.ajax, etc.
Can anyone tell me how I would call the javascript function named in the variable, please?
The name of the function is in a variable because the URL used to load the page fragment (which gets inserted into the current page) contains the name of the function to call.
I am open to other suggestions on how to implement this solution.
I'd avoid eval.
To solve this problem, you should know these things about JavaScript.
.
rather than square brackets []
, or vice versa.Your problem is a result of considering the dot manner of reference rather than the square bracket manner.
So, why not something like,
window["functionName"]();
That's assuming your function lives in the global space. If you've namespaced, then:
myNameSpace["functionName"]();
Avoid eval, and avoid passing a string in to setTimeout and setInterval. I write a lot of JS, and I NEVER need eval. "Needing" eval comes from not knowing the language deeply enough. You need to learn about scoping, context, and syntax. If you're ever stuck with an eval, just ask--you'll learn quickly.