Call a function inside a script include using a variable

hermanwinkel
Giga Contributor

i have a script include that has 3 functions. lets call them function a, b and c

from function a i want to call function b OR c depending on a variable given by the businessrule thats calling function a.

the variable has the function b or c as value.

is it possible to call the function like this inside function a, with a variable? I know I can code around it with a IF, but i have 20 more functions that can be called. so i would get 20 IF statements.

a : function(functioName) {

do something...

var callFunction = functionName+'()';   // callFunction = 'b()'   or 'c()'

var value = this.callFunction; // this will go to the function b or c

},

b : function {

do something

},

c : function {

do something else

}

thank you in advance

1 ACCEPTED SOLUTION

hermanwinkel
Giga Contributor

I found a solution.



i have to use the javascript funtion eval() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval



this way i can execute a string as javascript!


View solution in original post

5 REPLIES 5

Hm... eval() is generally considered not a good option. Have you tried



var callFunction = 'b'; // or 'c'


this[callFunction]();



In JavaScript, this.method() is the same as this['method']() Then you can specify the function name as a string.