Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a JavaScript method based on a variable value?

Tags:

javascript

I have method a(), method b(), and method c(). I will get a response message from server, which contains a or b or c and so on. If the response message is a, then I need to call method a(). If the response message is b, then I need to call method b() And so on...

I don't want to write any if else conditions or switch case to identify the method.

I don't want to do this:

if(res == 'a')
   a();
else if(res == 'b')
   b();

Instead of that I need something like reflections in Java.

like image 200
Prasath Avatar asked Apr 28 '26 12:04

Prasath


1 Answers

If you have defined the function in Global/window Scope then you can directly use res variable

window[res]();

Otherwise define the function in object and then use it

var obj = {
    a : function(){},
    b : function(){}
}   
obj[res]();
like image 63
Satpal Avatar answered Apr 30 '26 01:04

Satpal