Executing a function by name, passing an object as a parameter

拈花ヽ惹草 提交于 2020-01-02 21:57:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!