JavaScript: dynamically call functions

Sometimes you need to call a Javascript function but only know which one will be called at runtime. So you cannot directly call the function in you code but need to some get a function in a variable and be able to use it to call the appropriate function.

Of course a simple solution is to use a if-then-else (or a switch) e.g.:

function func_abc() {
	alert("abc");
}
function call_others(function_name) {
	if (function_name == "abc") {
		func_abc();
	}
}
call_others("abc");

The problem is that you need to keep changing the call_others function every time you add a new function which can be called. And in my case I do not even know which functions are all available. I can compute the name of the function but do not know which functions are available.

So what I need is to execute a function with dynamically computed function name. One candidate for this is the eval function. Here the definition of the eval function at w3schools:

Syntax: eval(string)

Parameter Values:

Parameter Description
string A JavaScript expression, variable, statement, or sequence of statements

You can use it this way:

function func_abc() {
	alert("abc");
}
function call_others(function_name) {
	eval("func_"+function_name+"()");
}
call_others("abc");

This works pretty well. But even though the eval function can be very useful in some cases, if you can do without it, you should. And in this case there is an alternative.

The alternative is to go through the window object. In JavaScript everything that is defined in the global scope is defined as a property of the global window object. So the func_abc function defined about is defined as window.func_abc. Also in JavaScript properties of objects can be accessed using an associative array syntax e.g. window.abc and window[“abc”] are equivalent. So you can access func_abc using window[“func_abc”].

So you can implement call_others like this:

function call_others(function_name) {
	window["func_"+function_name]();
}

Note that if your functions are not global functions but functions of an object you can also use a similar solution e.g.:

function MyClass() {
	this.abc = function() {
		alert("abc");
	}
}

var myObject = new MyClass();
myObject["abc"]();

If what you want to do is not only dynamically call a function but also dynamically create a named function, it is also best done with the window object using either:

window['name'] = function() { ... }

or:

window['name'] = new Function('...')

3 thoughts on “JavaScript: dynamically call functions

  1. How about creating a self invoking function that returns a method depending on a condition?

    var myFunction = function () {
    var foo = function () {
    ..code
    };
    var bar = function () {
    …code
    };

    return condition === value ? foo : bar;
    } ();

    now myFunction will use the reference passed to it in the self invoking function.

    1. This is of course a way to handle a situation where you have a finite number of functions you could call. Unfortunately it wasn’t an option in my case since I was working on a project where additional functions would be loaded dynamically and you could have any number of functions being called depending on the value of a string parameter. In such cases you need to be able to interpret the string or the results of a string operation on the parameter to determine which function should be called. I didn’t know in advance which pool of functions could be called.

  2. Thank you very much ..
    It really really helped.

    Here is my dynamic ajax which might help someone, I hope.

    /*****************DYNAMIC AJAX CALLING*******************/
    function CallDynamicAjaxAsync(URLToCall, Parameters, FuncCallBack) {

    var RETURNVAL = [];
    $.ajax({
    url: URLToCall,
    data: Parameters,
    dataType: “json”,
    type: “POST”,
    async: true,
    contentType: “application/json; charset=utf-8”,
    success: function (data) {
    RETURNVAL.push(1);
    RETURNVAL.push(JSON.parse(data.d));

    window[“”+FuncCallBack](RETURNVAL, ‘false’);
    },
    error: function (response) {
    RETURNVAL.push(0);
    RETURNVAL.push(response.responseText);
    window[“” + FuncCallBack](RETURNVAL, ‘true’);
    },
    failure: function (response) {
    RETURNVAL.push(0);
    RETURNVAL.push(response.responseText);
    window[“” + FuncCallBack](RETURNVAL, ‘true’);
    }
    });
    //return RETURNVAL;
    }

    Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *