How to call a javascript function when the name is stored as a variable

Question

In Javascript, how does one call a function when the name of the function is stored as a string in a variable, such as this :

var tmp = "function_name";

This is something I often encounter, especially when building larger AJAX applications where you’d like to be able to pass along the name of a function to call when the AJAX call completes, so I thought I’d post a quick note as reference.

Answer

The way to call the function is like this:

function myfunc() { alert('hi'); }
var tmp = "myfunc";
window[tmp]();

Or to demonstrate when your functions live in an object :

var ANVIL = {
    run : function (callbackFunction) {
        ANVIL[callbackFunction]();
    } ,
    mycallback : function () {
        alert('success');
    }
}
ANVIL.run('mycallback');

Leave a Reply