0

I have a function name = "test".

How do I call this.test() function in a class knowing the function name?

I'm guessing I can use the eval() function but that is not working?

How can I call a class function using only the string name in javascript?

Brown Limie
  • 2,249
  • 3
  • 17
  • 18

3 Answers3

1

Use bracket notation.

this["test"](/* args */);

or

name = "test";
this[name](/* args */);
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
1

To call the function just as a plain function without the object as context, just get the reference to it and call it. Example:

var name = "test";
var f = obj[name];
f(1, 2);

To call it as a method of the object, get a reference to the function then use the call method to call it to set the context. Example:

var name = "test";
var f = obj[name];
f.call(obj, 1, 2);

If you are inside a method of the object, you can use this instead of the object reference obj that I used above.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

To make you code more safe, I recommend you to check that it is a function.

var a='functionName'
if (typeof this[a]!='function')
  alert('This is not a function')
else
  this[a]()
Aminadav Glickshtein
  • 23,232
  • 12
  • 77
  • 117