Search code examples
javascriptstringfunctionreflectionreference

How do I convert a string to a function reference in JavaScript?


What I want is to pass a function's name as a string and have that be as if I passed a reference to the function. For example, I want to make this:

var test = function(fn){
  fn();
}
test(alert);

Equal to this:

var test = function(function_as_string){
    //...code that converts function_as_string to function reference fn
    fn();
}
test('alert');

How can I do this?


Solution

  • You get the function reference from the window object:

    var fn = window[function_as_string];
    

    Demo: http://jsfiddle.net/Guffa/nA6gU/