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?
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?
Use bracket notation.
this["test"](/* args */);
or
name = "test";
this[name](/* args */);
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.
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]()