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?
You get the function reference from the window object:
var fn = window[function_as_string];
Demo: http://jsfiddle.net/Guffa/nA6gU/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With