问题
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
回答1:
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 );
回答2:
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"]);
来源:https://stackoverflow.com/questions/1676583/executing-a-function-by-name-passing-an-object-as-a-parameter