I know there are a few similar questions already on SO
(1, 2, 3) but unfortunately my limited knowledge of JS
doesn't allow me to extrapolate the scenarios to my personal use case, hence this question.
I have the following piece of code which allows me to dynamically attach to and call from an object some functions, which works fine (available on JsFiddle
):
JavaScript:
$.extend(true, window, {
"MyPlugin": {
"dynamicFunction": dummy_function
}
});
function dummy_function() {
}
function real_function(string) {
alert(string);
}
function dynamic_call(function_name, text) {
MyPlugin["dynamicFunction"] = eval(function_name);
MyPlugin["dynamicFunction"](text);
}
HTML:
<button onClick="dynamic_call('real_function','some text');">click me</button>
UPDATE:
Funny enough, I was trying to replicate an issue I have whereby my function is scoped locally, but I ended writing an example where it isn't :) (I told you JS
isn't my thing). Therefore all window[function_name]
answers are correct, although I accepted James Allardice
's because he extrapolated to the issue I was trying to resolve but didn't raise.
How can I achieve the same functionality without the use of eval
?