0

I am trying to call a function using a variable with it's name.

Here's the code:

var selectedFunc = 'func2';

var myModule = {

    func1: function() {
       //something here  
    },

    func1: function() {
       //something here 
    }

};

myModule.selectedFunc();

I would normally do this:

myModule.func1();

which will work but I'm trying to use the variable to define it's name, which is not working.

How can I fix this issue?

Satch3000
  • 44,076
  • 86
  • 209
  • 342

3 Answers3

5

You can use bracket notation:

myModule[selectedFunc]();
tymeJV
  • 102,126
  • 13
  • 159
  • 155
0

Use eval.

var selectedFunc = 'func2';

var myModule = {

    func1: function() {
       return "hello";
    },

    func2: function() {
       return "world"; 
    }

};

window.alert(eval("myModule." + selectedFunc + "()"));
Samuel Toh
  • 16,166
  • 3
  • 21
  • 36
0

You could call it using the following syntax

setTimeout("myModule."+selectedFunc + "()", 0);

Or even using eval to call it

eval("myModule." + selectedFunc).call();
Muhammad Soliman
  • 18,833
  • 5
  • 99
  • 70