This question already has an answer here:
I got a string like:
settings.functionName + '(' + t.parentNode.id + ')';
that I want to translate into a function call like so:
clickedOnItem(IdofParent);
This of course will have to be done in JavaScript. When I do an alert on settings.functionName + '(' + t.parentNode.id + ')';
it seems to get everything correct. I just need to call the function that it would translate into.
Legend:
settings.functionName = clickedOnItem
t.parentNode.id = IdofParent
it is extensively used when dealing with JSON.
This took me a while to figure out, as the conventional
window['someFunctionName']()
did not work for me at first. The names of my functions were being pulled as an AJAX response from a database. Also, for whatever reason, my functions were declared outside of the scope of the window, so in order to fix this I had to rewrite the functions I was calling fromto
and from there I could call
window['someFunctionName']()
with ease. I hope this helps someone!I wanted to be able to take a function name as a string, call it, AND pass an argument to the function. I couldn't get the selected answer for this question to do that, but this answer explained it exactly, and here is a short demo.
This also works with multiple arguments.
Based on Nicolas Gauthier answer:
In javascript that uses the CommonJS spec, like node.js for instance you can do what I show below. Which is pretty handy for accessing a variable by a string even if its not defined on the
window
object. If there is a class namedMyClass
, defined within a CommonJS module named MyClass.jsYou can then do this nice bit o witchcraft from another file called MyOtherFile.js
One more reason why CommonJS is such a pleasure.
While I like the first answer and I hate eval, I'd like to add that there's another way (similar to eval) so if you can go around it and not use it, you better do. But in some cases you may want to call some javascript code before or after some ajax call and if you have this code in a custom attribute instead of ajax you could use this:
Or eventually store this in a function cache if you may need to call it multiple times.
Again - don't use eval or this method if you have another way to do that.