I am running a self executing function in javascript to not interfere with any global variables on a page. I have a string with the name of a function I want to call. The function is declared inside my self-executing function. Is there a way to call that function by using the string?
(function(document, window){
var functionName = "myFunction";
window[functionName](); //This does not work...
function myFunction(){
//Do some stuff
}
}(document, window)
I found this: How to execute a JavaScript function when I have its name as a string
but my function is self executing without a name, so I have no way to reference it with the window variable.
This is just a cleaner version of what others have suggested, no global pollution, no eval, and no obscure variable references (arguments.callee and "this").
// Not sure why you were passing in doc and window, so I took it out for clarity
(function(){
var funcs = {
funcA: function () { return "a"},
funcB: function () { return "b"}
};
var functionName = "funcA";
funcs[functionName]();
}();
This approach does require you to declare the functions before you use them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With