Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 294
Aust Avatar asked Sep 15 '12 23:09

Aust


2 Answers

You get the function reference from the window object:

var fn = window[function_as_string];

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

like image 196
Guffa Avatar answered Sep 20 '22 00:09

Guffa


Use eval to get a reference to the function -

var Namespace = {
    quack: function () {console.log('quack!')}
};

function test (fnName) {
    var fn = eval(fnName);
    fn();
}
test('Namespace.quack')

This could potentially allow you to pass other arguments in if you wanted to.

Oh, and the reason that you may not be able to simply use window[fnName] is if it's something like $.ajax - window['$.ajax'] will give you undefined.. so unless you want to create a complex function for looking up whether or not it's in another namespace, eval is your best bet.

like image 22
Stephen Avatar answered Sep 19 '22 00:09

Stephen