1

Here's the problem - I know function by name (and that function has already been loaded form an external script), but I don't have an actual function object avail for me to call. Normally I would call eval(function_name + "(arg1, arg2)"), but in my case I need to pass an object to it, not a string. Simple example:

var div = document.getElementById('myDiv')
var func = "function_name" -- this function expects a DOM element passed, not id

How do I execute this function?

Thanks! Andrey

Andrey
  • 20,487
  • 26
  • 108
  • 176
  • 1
    See http://stackoverflow.com/questions/359788/javascript-function-name-as-a-string and http://stackoverflow.com/questions/496961/how-do-i-call-a-javascript-function-name-using-a-string and http://stackoverflow.com/questions/912596/how-to-turn-a-string-into-a-javascript-function-call and the list goes on... – Crescent Fresh Nov 04 '09 at 21:02
  • My bad, I guess I didn't search good enough before asking – Andrey Nov 04 '09 at 21:07

2 Answers2

5

Never use eval, it´s evil (see only one letter difference) You can simply do:

var div = document.getElementById('myDiv');
var result = window[function_name](div);

This is possible because functions are first class objects in javascript, so you can acces them as you could with anyother variable. Note that this will also work for functions that want strings or anything as paramter:

var result = window[another_function_name]("string1", [1, "an array"]);
Pim Jager
  • 31,965
  • 17
  • 72
  • 98
4

You should be able to get the function object from the top-level window. E.g.

var name = "function_name";
var func = window[name];
func( blah );
friedo
  • 65,762
  • 16
  • 114
  • 184