1

I have an class called myObject, which has multiple methods, one of which is add. I am using another function with an argument for which function of myObject I want to use. If I want to use add, I pass it 'add.' If I want to use delete, I'd pass it 'delete,' etc. In the definition of the function test, if I use obj.add it works fine, but if I use obj.func, the passed parameter, it doesn't work. I tested to make sure func = add, and it is, but for some reason it won't work with the parameter. Any ideas what I am doing wrong?

testObj = new myObject();
test(testObj, 'add', 3);


function test(obj, func, parm){
     var answer = obj.func(parm);
}
The_DemoCorgin
  • 744
  • 6
  • 19

1 Answers1

2

Because of the way objects work in javascript. obj.func will try to run a function in obj called func. However if you remember that all objects in javascript are functions. Then you can do this: obj[func] which will evaluate the funct variable and look for the method in obj with that evaluated name.

testObj = new myObject();
test(testObj, 'add', 3);


function test(obj, func, parm){
     var answer = obj[func](parm);
}
matt
  • 1,680
  • 1
  • 13
  • 16