简体   繁体   English

通过名称执行函数,将对象作为参数传递

[英]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. 通常,我会调用eval(function_name +“(arg1,arg2)”),但就我而言,我需要向其传递一个对象,而不是字符串。 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 安德烈

Never use eval, it´s evil (see only one letter difference) You can simply do: 永远不要使用eval,它是邪恶的(仅能看到一个字母的不同),您可以执行以下操作:

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. 这是可能的,因为函数是javascript中的一流对象,因此您可以像使用任何其他变量一样访问它们。 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 . 您应该能够从顶级window获取功能对象。 Eg 例如

var name = "function_name";
var func = window[name];
func( blah );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM