Brown Limie
Brown Limie

Reputation: 2599

how do I call a function within a class knowing the function name?

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?

Upvotes: 0

Views: 65

Answers (3)

Aminadav Glickshtein
Aminadav Glickshtein

Reputation: 24630

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]()

Upvotes: 0

Guffa
Guffa

Reputation: 700730

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.

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 191037

Use bracket notation.

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

or

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

Upvotes: 1

Related Questions