JavaScript: Call Function based on String

Tuesday, April 29, 2008 @ 7:38 AM

Wondering about calling a function from a string in JavaScript (including ActionScript in Flash/Flex)? Lest you forget, the language contains very few operators/keywords and is yet dynamic to the core. Practically everything is an object, even functions, and you can grab almost any property of said objects using the square-bracket syntax:

var s = "hello";
var s2 = this['s'];

Thus to call a function based on a string, you merely need to pull it off of an object and put the name in square brackets. If you're at the global level, or want a global function, you can use what I call the global context or global this reference:

function foo() { }

this["foo"]();

Obviously you could use a variable in place of the string literal:

var funcname = "foo";
this[funcname]();

If you're calling a function on an object instance, even an ActiveX/COM object in JScript, just put that object name followed by the function name in subscript form:

// in WSH/JScript ...
WScript["Echo"]("Hello World!");

// in web browser ...
document["write"]("Hello World!");

Since you're just trying to resolve down to a function-type, you can chain these together:

this["document"]["write"]("Bit contrived...");

When trying to call a global function from inside object methods you'll find the this reference is for that current instance of the object and not the global namespace. In that case you'll need to have either cached the global context or you can get it by calling any function without object context and have it return this, like so:

var gthis = (function(){return this;})();
In the above code I'm creating an anonymous function and executing it at the same time.
By Neil C. Obremski

Unveil Tools | Internet Domains Directory | Walk in the Woods, LLC