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
  • 1,829
  • 3
  • 14
  • 17

3 Answers3

1

Use bracket notation.

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

or

name = "test";
this[name](/* args */);
Daniel A. White
  • 181,601
  • 45
  • 354
  • 430
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
  • 666,277
  • 106
  • 705
  • 986
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
  • 20,647
  • 11
  • 72
  • 114