如何动态调用JavaScript对象的方法 [英] How do I dynamically call a JavaScript object's method
本文介绍了如何动态调用JavaScript对象的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我认为我在这里遗漏了一些非常简单的东西.我想将一个对象和方法传递给函数.这篇文章的原因太长了. :-)
I think that I'm missing something very simple here. I want to pass a function an object and the method to call. The reasons why are too long for this post. :-)
var myObj = new someObject();
var funcName = "hide";
function callObject(myObj,funcName){
obj.hide(); //this works
obj[funcName]; //doesn't work
obj.eval(funcName); //doesn't work either.. tried many variations
}
谢谢!
推荐答案
您需要在通话中加上括号,如下所示:
You need the parenthesis on the call, like this:
obj[funcName]();
您可以像这样工作:
eval("obj." + funcName + "()");
,但是有很多原因不这样做(安全性,性能,更难调试).
but there are many reasons not to do that (security, performance, harder debugging).
这篇关于如何动态调用JavaScript对象的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文