如何动态调用 JavaScript 对象的方法
我认为我在这里遗漏了一些非常简单的东西。我想传递一个函数、一个对象和要调用的方法。原因对于这篇文章来说太长了。 :-)
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
}
谢谢你!
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
}
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要在调用时使用括号,如下所示:
您可以让 eval 像这样工作:
但有很多理由不这样做(安全性、性能、更难的调试)。
You need the parenthesis on the call, like this:
You can get eval to work like this:
but there are many reasons not to do that (security, performance, harder debugging).
处理 obj[funcName](); 时,您必须处理对象的实例。如果您想在函数调用内使用对象的私有属性,它将使用它,因为它是静态属性。
When dealing with
obj[funcName]();
you have to take care of the instance of the object. if you want to use a private propetry form the object inside function call, it will use it as it was a static property.