This question already has an answer here:
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.
Definitely avoid using
eval
to do something like this, or you will open yourself to XSS (Cross-Site Scripting) vulnerabilities.For example, if you were to use the
eval
solutions proposed here, a nefarious user could send a link to their victim that looked like this:http://yoursite.com/foo.html?func=function(){alert('Im%20In%20Teh%20Codez');}
And their javascript, not yours, would get executed. This code could do something far worse than just pop up an alert of course; it could steal cookies, send requests to your application, etc.
So, make sure you never
eval
untrusted code that comes in from user input (and anything on the query string id considered user input). You could take user input as a key that will point to your function, but make sure that you don't execute anything if the string given doesn't match a key in your object. For example:This will fail if the
funcToRun
variable doesn't point to anything in themyFuncs
object, but it won't execute any code.This is kinda ugly, but its the first thing that popped in my head. This also should allow you to pass in arguments:
If you don't need to pass in arguments this might be simpler.
Standard dry-code warning applies.
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,
That's assuming your function lives in the global space. If you've namespaced, then:
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.
If it´s in the global scope it´s better to use:
than
eval()
. Becauseeval()
is evaaaaaal.Exactly like Nosredna said 40 seconds before me that is >.<