How to dynamically call a JavaScript object method

I think that here I am missing something very simple. I want to pass a function to an object and a call method. The reasons 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 } 

Thanks!

+6
javascript eval
source share
2 answers

You need a bracket to call, for example:

 obj[funcName](); 

You can get eval to work like this:

 eval("obj." + funcName + "()"); 

but there are many reasons not to do this ( security, performance, more complicated debugging ).

+15
source share

When working with obj[funcName](); you need to take care of the instance of the object. if you want to use a private proposition, form an object inside the function call, it will use it, since it is a static property.

+1
source share

All Articles