If you are doing some more advanced JavaScript applications, you’ll likely run into the problem at one point or another when you need to dynamically generate the name of a function you wish to call. This is the equivalent of PHP’s call_user_func().
Here’s how you can do it.
// Define some vars var foo = "hello"; var bar = "world"; var function_name = "say_" + foo + bar; // Since its name is being dynamically generated, always ensure your function actually exists if (typeof(window[function_name]) === "function") { window[function_name](" World!"); } else { throw("Error. Function " + function_name + " does not exist."); } function say_helloworld(the_word) { alert("Hello " + the_word); } // Browser will alert "Hello World!"
When you think about it, it makes a lot of sense considering all global objects in JavaScript are actually properties of the “window” object. Take a look at this example to understand that concept a bit more.
var foo = "apple"; function foobar() { var foo = "orange"; alert(window["foo"]); // alerts "apple" alert(foo); // alerts "orange" alert(window["foobar"]); // alerts the foobar function } foobar();
Here’s another example of when using a string to call a function could come in handy. This time we’re calling the property of an object we’ve created.
function Person() { this.message = "Hello World!"; this.say_hello = function(to) { alert(this.message); } } var Derek = new Person(); function_name = "say_hello"; Derek[function_name]();
See how it looks pretty much the same as the method above using a global function?
Hope that shed some light on your problem.