6

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!

David
  • 115
  • 2
  • 8

2 Answers2

15

You need the parenthesis on the call, like this:

obj[funcName]();

You can get eval to work like this:

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

but there are many reasons not to do that (security, performance, harder debugging).

Community
  • 1
  • 1
Samuel Neff
  • 73,278
  • 17
  • 138
  • 182
  • Thank you! I knew I was missing something simple. I really thought I tried obj[funcName]() before but it is working for me now. – David Feb 25 '11 at 02:00
  • 2
    Do use `eval` with care though :) http://stackoverflow.com/questions/86513/why-is-using-javascript-eval-function-a-bad-idea – o.k.w Feb 25 '11 at 02:02
  • See [my comment](http://stackoverflow.com/questions/5112793/how-do-i-dynamically-call-a-javascript-objects-method/5112938#5112938) on the security of using eval and other options without eval. Also, in addition to being insecure, eval can be very inefficient, especially when you do proper input validation, but even without validation you're calling the compiler every time you run it. – rsp Feb 25 '11 at 04:55
1

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.

Sangoku
  • 1,588
  • 2
  • 21
  • 50