Executing a function by name, passing an object as a parameter
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 eleme开发者_开发技巧nt passed, not id
How do I execute this function?
Thanks! Andrey
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"]);
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 );
精彩评论